You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LSTM模型训练报错:NumPy数组无法转换为Tensor问题求助

解决LSTM训练时的NumPy转Tensor错误(ValueError: Unsupported object type numpy.ndarray)

错误根源

你的代码中,create_sequences函数生成的序列已经是LSTM要求的**(样本数, 时间步长, 特征数)**格式(当window_size=1时,形状为(n_samples, 1, 3)),但后续执行的reshape(-1, 1)操作破坏了这个结构:

  • 该操作将序列数组重塑为(n_samples, 1),每个元素是一个形状为(1,3)的NumPy数组
  • 整个数组的 dtype 变为object,TensorFlow无法处理这种嵌套的object类型数组,因此抛出转换错误

修复步骤

1. 删除错误的重塑操作

直接移除以下两行代码:

sequences2 = sequences2.reshape(-1, 1)
sequences3 = sequences3.reshape(-1, 1)

create_sequences返回的序列已经符合LSTM的输入格式要求。

2. 验证序列形状

在生成序列后添加打印语句,确认形状正确:

print(sequences2.shape)  # 预期输出:(样本数量, 1, 3)

3. (可选)优化模型输入形状定义

模型的input_shape可以直接指定为(window_size, 3)(因为固定使用3个特征),或者保留(window_size, sequences.shape[2]),两种方式都能正常工作。

修复后的完整代码片段

# Load CSV data # 3 features (1, 2, 3), 1 label (5) columns
# All data is in float and 1,0 in Labels
data = pd.read_csv("data_1.csv", usecols=["Column_1","Column_2","Column_3","Column_5"]) 
data2 = pd.read_csv("data_2.csv", usecols=["Column_1","Column_2","Column_3","Column_5"])

window_size = 1  # For timesteps

# Function to create sequences
def create_sequences(data, window_size, label_col):
  sequences = []
  labels = []
  for i in range(len(data) - window_size + 1):
    window = data.loc[i:i+window_size,["Column_1","Column_2","Column_3"]].astype('float64')
    label = data.loc[i + window_size - 1, label_col]  # Label at the end of window
    sequences.append(window.to_numpy())
    labels.append(label)
  return np.array(sequences), np.array(labels)

# Create sequences and labels
sequences2, labels2 = create_sequences(data, window_size, "Column_5")
# 移除错误的reshape
print("Data 1 preparation is done")
print(sequences2.shape)  # 确认形状

sequences3, labels3 = create_sequences(data2, window_size, "Column_5")
# 移除错误的reshape
print("Data 2 preparation is done")
print(sequences3.shape)  # 确认形状

sequences = np.concatenate((sequences2, sequences3))
labels = np.concatenate((labels2, labels3), axis=0)

# Define LSTM model
model = keras.Sequential([
  keras.layers.LSTM(64, return_sequences=True, input_shape=(window_size, sequences.shape[2])),
  keras.layers.LSTM(32),
  keras.layers.Dense(len(np.unique(labels)), activation='softmax')  # Multi-class output
])

# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(sequences, keras.utils.to_categorical(labels), epochs=1)

额外验证

修复后可以检查序列数组的 dtype,确认不再是object:

print(sequences.dtype)  # 预期输出:float64

内容的提问来源于stack exchange,提问作者Athul Srinivas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:53:14