gpt4 book ai didi

machine-learning - Dense 层中的 Keras 错误,预期 4 维得到形状为 (1024,2) 的数组

转载 作者:行者123 更新时间:2023-11-30 09:34:10 27 4
gpt4 key购买 nike

我正在尝试使用 Keras 和启用 GPU 的 Tensorflow 后端来训练 3 层密集神经网络模型。

我拥有的数据集是 400 万张 20x40px 图像,我将它们放置在目录中,并以它们所属的类别名称命名。

由于数据量很大,我无法将其全部加载到 RAM 中并将其输入到我的模型中,因此我考虑使用 Keras's ImageDataGenerator ,具体来说,函数 flow_from_directory() 就可以解决这个问题。这会产生一个 (x, y) 元组,其中 x 是图像的 numpy 数组,y 是图像的标签。

我希望模型知道访问作为模型输入的 numpy 数组,因此我将输入形状设置为:(None,20,40,3),其中 None 是批量大小,20 和 40是图像的大小,3 是图像中的 channel 数。但这不起作用,因为当我尝试训练我的模型时,我不断收到错误:ValueError:检查目标时出错:预期dense_3有4个维度,但得到的数组形状为(1024, 2)

我知道原因是它从 flow_from_directoy 获取元组,我想我可以更改输入形状以匹配,但是,我担心这会使我的模型毫无用处,因为我将使用图像进行预测而不是预先分类的元组。所以我的问题是,如何让 flow_from_directory 将图像提供给我的模型,并且仅使用元组来验证其训练?我在这里误解了什么吗?

作为引用,这是我的代码:

from keras.models import Model
from keras.layers import *
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import TensorBoard

# Prepare the Image Data Generator.
train_datagen = ImageDataGenerator()
test_datagen = ImageDataGenerator()

train_generator = train_datagen.flow_from_directory(
'/path/to/train_data/',
target_size=(20, 40),
batch_size=1024,
)

test_generator = test_datagen.flow_from_directory(
'/path/to/test_data/',
target_size=(20, 40),
batch_size=1024,
)

# Define input tensor.
input_t = Input(shape=(20,40,3))

# Now create the layers and pass the input tensor to it.
hidden_1 = Dense(units=32, activation='relu')(input_t)
hidden_2 = Dense(units=16)(hidden_1)
prediction = Dense(units=1)(hidden_2)

# Now put it all together and create the model.
model = Model(inputs=input_t, outputs=prediction)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

# Prepare Tensorboard callback and start training.
tensorboard = TensorBoard(log_dir='./graph', histogram_freq=0, write_graph=True, write_images=True)
print(test_generator)
model.fit_generator(
train_generator,
steps_per_epoch=2000,
epochs=100,
validation_data=test_generator,
validation_steps=800,
callbacks=[tensorboard]
)

# Save trained model.
model.save('trained_model.h5')

最佳答案

对于密集层,您的输入形状是错误的。

密集层期望输入形状为(无,长度)。

您需要 reshape 输入,使它们成为向量:

imageBatch=imageBatch.reshape((imageBatch.shape[0],20*40*3))

或者使用卷积层,它需要输入形状类型(None,nRows,nCols,nChannels),就像tensorflow中一样。

关于machine-learning - Dense 层中的 Keras 错误,预期 4 维得到形状为 (1024,2) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47860327/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com