簡體   English   中英

'{{node conv2d_3/Conv2D} 從 1 中減去 3 導致的負維度大小

[英]Negative dimension size caused by subtracting 3 from 1 for '{{node conv2d_3/Conv2D}

你好,這是我第一次制作 model 雖然我寫的代碼和我在課程中看到的完全一樣,但我收到了這個錯誤,我不知道該怎么做

這是代碼:

from __future__ import  print_function
import keras
from keras.optimizers import Adadelta
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten
from keras.layers import Conv2D,MaxPool2D
from keras import backend as k

batch_size=128
num_classes=10
epochs=12
img_rows=28;img_cols=28
(x_train,y_train),(x_test,y_test)=mnist.load_data()

if k.image_data_format()=="channels_first":
  x_train=x_train.reshape(x_train.shape[0],img_rows,img_cols)
  x_test=x_test.reshape(x_test.shape[0],img_rows,img_cols)
  input_shape=(1,img_rows,img_cols)
else:
  x_train=x_train.reshape(x_train.shape[0],1,img_rows,img_cols)
  x_test=x_test.reshape(x_test.shape[0],1,img_rows,img_cols)
  input_shape=(1,img_rows,img_cols)
x_train=x_train/255.0
x_test=x_test/255.0
y_train=keras.utils.to_categorical(y_train,num_classes)
y_test=keras.utils.to_categorical(y_test,num_classes)

model=Sequential()
model.add(Conv2D(32,kernel_size=(3,3),activation="relu",input_shape=input_shape))
model.add(Conv2D(64,kernel_size=(3,3),activation="relu"))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(128,activation="relu"))
model.add(Dense(10,activation="softmax"))
#model.build()
model.summary()
model.compile(loss=keras.losses.CategoricalCrossentropy,optimizer="Adadelta",metrics=["accuracy"])
model.fit(x_train,y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test,y_test))



ValueError: Negative dimension size caused by subtracting 3 from 1 for '{{node conv2d_3/Conv2D}} = Conv2D[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], explicit_paddings=[], padding="VALID", strides=[1, 1, 1, 1], use_cudnn_on_gpu=true](Placeholder, conv2d_3/Conv2D/ReadVariableOp)' with input shapes: [?,1,28,28], [3,3,28,32].

您傳遞了錯誤的輸入形狀:您將通道尺寸放在高度和寬度之前。 這是你通過的:

n_samples, channels, height, width

您應該改為使用:

n_samples, height, width, channels

這是你犯錯誤的地方:

x_train=x_train.reshape(x_train.shape[0],1,img_rows,img_cols)
x_test=x_test.reshape(x_test.shape[0],1,img_rows,img_cols)
input_shape=(1,img_rows,img_cols)

更改這些以將頻道放在最后。

x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)

更好的方法是使用np.expand_dimstf.expand_dims

x_train = np.expand_dims(x_train, -1)

這會將形狀(60000, 28, 28)轉換為(60000, 28, 28, 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM