【问题标题】:Keras shape of features for training用于训练的 Keras 形状特征
【发布时间】:2016-09-19 05:47:46
【问题描述】:

我正在尝试使用 keras train_on_batch 函数训练 nn。我有 39 个功能,并且希望一批包含 32 个样本。因此,每次训练迭代我都有一个包含 32 个 numpy 数组的列表。

这是我的代码(这里每个 batch_x 是一个包含 32 个 numpy 数组的列表,每个数组包含 39 个特征):

input_shape = (39,)

model = Sequential()
model.add(Dense(39, input_shape=input_shape)) # show you is only first layer
... 

for batch_x, batch_y in train_gen:
    model.train_on_batch(batch_x, batch_y)

但是我突然报错了:

Exception: Error when checking model input: the list of Numpy arrays
that you are passing to your model is not the size the model expected.
Expected to see 1 arrays but instead got the following list of 32 arrays:

我不太确定出了什么问题。

附:我还尝试了不同的input_shape,例如 (32, 39)、(39, 32) 等。

【问题讨论】:

    标签: python python-2.7 machine-learning keras training-data


    【解决方案1】:

    您不想要 32 个大小为 39 的数组,您想要一个大小为 (32, 39) 的数组。

    因此您必须将 input_shape 更改为 (None, 39),None 允许您动态更改 batch_size,并将 batch_x 更改为形状为 (32, 39) 的 numpy 数组。

    【讨论】:

      【解决方案2】:

      在 Keras 中,第一个参数是 输出 而不是 输入 维度。 Keras docs 头版示例非常清楚:

      model.add(Dense(output_dim=64, input_dim=100))
      

      调整该示例以符合我猜是您的要求:

      model.add(Dense(output_dim=39, input_dim=39))
      

      在您的代码中,Dense 层中的第一个位置 arg 是 39,它将 输出 设置为 39-D,而不是您可能假设的输入。你说你有 39 个输入特征。第一层(我试图复制您的意图)不会从您的 39 维输入特征向量中进行任何压缩或特征提取。

      您为什么不为每一层设置输入和输出数组的尺寸(如示例中所示),然后不考虑输入_shape?只是重塑您的输入(和标签)以匹配默认假设?此外,您可以尝试在输入数据集(或其中的一部分)上运行基本的 fit 方法,然后再进行更复杂的安排,例如像您所做的那样手动批量训练。

      这是一个关于你的特征维度的玩具问题的例子:

      from keras.models import Sequential
      from keras.layers import Dense, Activation
      from keras.regularizers import l1l2
      
      X = np.random.randn(1000, 39)
      y = np.array([X[i,7:13].sum() for i in range(X.shape[0])])
      
      nn = Sequential()
      nn.add(Dense(output_dim=1, input_dim=39))
      nn.compile('sgd', 'mse')
      nn.fit(X, y, nb_epoch=10)
      

      这给出了:

      Epoch 1/10
      1000/1000 [==============================] - 0s - loss: 4.6266      
      ...    
      Epoch 10/10
      1000/1000 [==============================] - 0s - loss: 1.4048e-04
      

      【讨论】:

        猜你喜欢
        • 2013-07-28
        • 2018-10-19
        • 2018-02-19
        • 2017-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        相关资源
        最近更新 更多