简体   繁体   English

在顺序Keras模型中将一维数据加载到密集层中

[英]Loading one dimensional data into a Dense layer in a sequential Keras model

I have the results of a trained model, ending in a Flatten layer in numpy output files. 我得到了经过训练的模型的结果,该结果以numpy输出文件的Flatten层结尾。 I try to load them and use them as inputs of a Dense layer. 我尝试加载它们并将它们用作密集层的输入。

train_data = np.load(open('bottleneck_flat_features_train.npy'))
train_labels = np.array([0] * (nb_train_samples / 2) + [1] * (nb_train_samples / 2))
#
validation_data = np.load(open('bottleneck_flat_features_validation.npy'))
validation_labels = np.array([0] * (nb_validation_samples / 2) + [1] * (nb_validation_samples / 2))
#
top_m  = Sequential()
top_m.add(Dense(2,input_shape=train_data.shape[1:], activation='sigmoid', name='top_dense1'))
top_m.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
#
top_m.fit(train_data, train_labels,
    nb_epoch=nb_epoch, batch_size=my_batch_size,
    validation_data=(validation_data, validation_labels))

However I get the following error message: 但是我收到以下错误消息:

    ValueError: Error when checking model target: expected top_dense1 to have
 shape (None, 2) but got array with shape (13, 1)

My input dimensions are (16,1536) - 16 images for this limited trail run, 1536 features. 我的输入尺寸是(16,1536)-此有限的越野跑的16幅图像,具有1536个特征。

>>> train_data.shape
(16, 1536)

The dense layer should expect a one dimensional 1536 long array. 致密层应具有一维1536长的阵列。

>>> train_data.shape[1]
1536

What should I do? 我该怎么办? Many thanks! 非常感谢!

您是否不想编译并拟合top_m而不是模型?

I have found my problem - I did not define the lables correctly. 我发现了我的问题-我没有正确定义标签。 I have switched the model compilation to a sparse categorical crossentropy mode. 我已将模型编译切换为稀疏分类交叉熵模式。

my current code is 我当前的代码是

def train_top_model():
    train_data = np.load(open('bottleneck_flat_features_train.npy'))
    train_labels = np.array([0] * (nb_train_samples / 2) + [1] * (nb_train_samples / 2))
#
    validation_data = np.load(open('bottleneck_flat_features_validation.npy'))
    validation_labels = np.array([0] * (nb_validation_samples / 2) + [1] * (nb_validation_samples / 2))
#
    top_m  = Sequential()
    top_m.add(Dense(2,input_shape=train_data.shape[1:], activation='softmax', name='top_dense1'))
    top_m.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
#
    top_m.fit(train_data, train_labels,
    nb_epoch=nb_epoch, batch_size=my_batch_size,
    validation_data=(validation_data, validation_labels))

Now it works and converges. 现在它可以工作并融合了。

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

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