繁体   English   中英

Keras形状的训练特征

[英]Keras shape of features for training

我正在尝试使用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:

我不太确定这是怎么回事。

PS我还尝试了不同的input_shape例如( input_shape ),( input_shape )等。

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

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

在Keras中, 输出而不是输入尺寸是第一个arg。 Keras文档首页示例非常清楚:

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维输入特征向量进行任何压缩或特征提取。

为什么不只为每一层设置输入和输出数组的尺寸(如示例中所示),而只保留input_ 形状呢? 只是重塑您的输入(和标签)以符合默认假设? 同样,您可以尝试在输入数据集(或输入数据集的某些部分)上运行基本的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM