简体   繁体   English

Keras/Tenserflow - 无法使 model.fit() 工作

[英]Keras/Tenserflow - Cannot make model.fit() work

I am trying to make a CNN network to make predictions on images of mushrooms.我正在尝试制作一个 CNN 网络来预测蘑菇的图像。

Sadly, I can't even begin to train my model, the fit() method always gives me errors.可悲的是,我什至无法开始训练我的 model,fit() 方法总是给我错误。

There are 10 classes, the tf Datasets correctly found their names based on their subfolders.有 10 个类,tf 数据集根据它们的子文件夹正确找到了它们的名称。

With my current code, it says:使用我当前的代码,它说:

InvalidArgumentError:  logits and labels must have the same first
dimension, got logits shape [12800,10] and labels shape [32]

Here's my code:这是我的代码:

#Data loading
train_set = keras.preprocessing.image_dataset_from_directory(
      data_path, 
      labels="inferred",
      label_mode="int",
      batch_size=32, 
      image_size=(64, 64),
      shuffle=True,
      seed=1446,
      validation_split = 0.2,
      subset="training")

validation_set = keras.preprocessing.image_dataset_from_directory(
  data_path, 
  labels="inferred",
  label_mode="int",
  batch_size=32, 
  image_size=(64, 64),
  shuffle=True,
  seed=1446,
  validation_split = 0.2,
  subset="validation")

#Constructing layers
input_layer = keras.Input(shape=(64, 64, 3))
x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(input_layer)
x = layers.MaxPooling2D(pool_size=(3, 3))(x)
x = keras.layers.ReLU()(x)
output = layers.Dense(10, activation="softmax")(x)

#Making and fitting the model
model = keras.Model(inputs=input_layer, outputs=output)
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=['accuracy'])
model.fit(train_set, epochs=5, validation_data=validation_set)

I think you need to flatten before passing to the Dense layer我认为你需要在传递到Dense层之前变平

input_layer = keras.Input(shape=(64, 64, 3))
x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(input_layer)
x = layers.MaxPooling2D(pool_size=(3, 3))(x)
x = keras.layers.ReLU()(x)
x = keras.layers.Flatten()(x) # try adding this
output = layers.Dense(10, activation="softmax")(x)

what you need to do is to add a flatten layer in your model between the ReLU layer and the output layer.您需要做的是在 ReLU 层和 output 层之间的 model 中添加一个展平层。

input_layer = keras.Input(shape=(64, 64, 3))
x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(input_layer)
x = layers.MaxPooling2D(pool_size=(3, 3))(x)
x = keras.layers.ReLU()(x)
x = keras.layers.Flatten()(x)
output = layers.Dense(10, activation="softmax")(x)

When you see model.fit throw an error due to the difference in logits and labels it is a good idea to print out the model summary当您看到 model.fit 由于 logits 和标签的差异而引发错误时,最好打印出 model 摘要

print(model.summary())

By looking at the summary it usually helps figure out what is wrong.通过查看摘要,它通常有助于找出问题所在。

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

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