做顺序模型时,张量流,lstm形状应该是什么?

时间:2019-08-06 21:12:57

标签: python tensorflow lstm

我的数据不断出现形状错误。我想训练一个lstm来预测正弦波,所以我生成数据

x_size = 100
xxx = [np.sin(5*np.pi*i/x_size)+.1*np.random.rand() for i in range(x_size)]
xxx = np.array(xxx)

这是一组100个样本,每个样本都是一维的。因此每个纪元中都会有100个数据点(由于它很小,所以现在还不必担心批量大小,但是我最终还是想进行批量训练)

然后尝试对其进行预测

model = tf.keras.Sequential()
model.add(layers.LSTM(128, activation='relu',))
model.add(layers.Dense(1, activation='relu'))

model.compile(loss='mean_squared_error', 
              optimizer='sgd',
              metrics=['accuracy'])

model.fit(xxx, xxx)

但是我无法运行fit步骤。我尝试过以其他方式重塑xxx,但是似乎没有任何效果。

有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

我将在重写示例中使用注释向您展示您的错误

# it should have a sample size N and a feature size (M, 1)
# thus x has shape = (N, M, 1)
# y as label shape = (N, 1) for the output size of your dense layer is 1
# x_size = 100
N = 100
M = 1
xxx = np.random.rand(N, M, 1)
y = np.random.randint(0, 1, size = (N, 1))
# xxx = [np.sin(5*np.pi*i/x_size)+.1*np.random.rand() for i in range(x_size)]
# xxx = np.array(xxx)

model = Sequential()
model.add(LSTM(128, activation='relu',))
model.add(Dense(1, activation='relu'))

model.compile(loss='mean_squared_error', 
              optimizer='sgd',
              metrics=['accuracy'])
# if you choose accuracy as metric, output feature size is normally 1
model.fit(xxx, y)