我正在嘗試制作一個 CNN 網路來對蘑菇的影像進行預測。
可悲的是,我什至無法開始訓練我的模型,fit() 方法總是給我錯誤。
有 10 個類,tf 資料集根據它們的子檔案夾正確找到了它們的名稱。
使用我當前的代碼,它說:
InvalidArgumentError: logits and labels must have the same first
dimension, got logits shape [12800,10] and labels shape [32]
型號概要:
Layer (type) Output Shape Param #
=================================================================
input_5 (InputLayer) [(None, 64, 64, 3)] 0
conv2d_4 (Conv2D) (None, 62, 62, 32) 896
max_pooling2d_2 (MaxPooling (None, 20, 20, 32) 0
2D)
re_lu_2 (ReLU) (None, 20, 20, 32) 0
dense_2 (Dense) (None, 20, 20, 10) 330
=================================================================
這是我的代碼:
#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)
uj5u.com熱心網友回復:
我認為你需要在傳遞到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)
uj5u.com熱心網友回復:
你需要做的是在你的模型中的 ReLU 層和輸出層之間添加一個 flatten 層。
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)
當您看到 model.fit 由于 logits 和標簽的差異而拋出錯誤時,最好列印出模型摘要
print(model.summary())
通過查看摘要,它通常有助于找出問題所在。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371399.html
