[英]ValueError: logits and labels must have the same shape ((1, 7, 7, 2) vs (1, 2))
I'm quite new to CNN.我对CNN很陌生。 I'm trying to create a the following model.
我正在尝试创建以下 model。 but I get the following error: "ValueError: logits and labels must have the same shape ((1, 7, 7, 2) vs (1, 2))"
但我收到以下错误:“ValueError: logits and labels must have the same shape ((1, 7, 7, 2) vs (1, 2))
Below the code I'm trying to implement在我尝试实现的代码下方
#create the training data set
train_data=scaled_data[0:training_data_len,:]
#define the number of periods
n_periods=28
#split the data into x_train and y_train data set
x_train=[]
y_train=[]
for i in range(n_periods,len(train_data)):
x_train.append(train_data[i-n_periods:i,:28])
y_train.append(train_data[i,29])
x_train=np.array(x_train)
y_train=np.array(y_train)
#Reshape the train data
x_train=x_train.reshape(x_train.shape[0],x_train.shape[1],x_train.shape[2],1)
x_train.shape
y_train = keras.utils.to_categorical(y_train,2)
# x_train as the folllowing shape (3561, 28, 28, 1)
# y_train as the following shape (3561, 2, 2)
#Build the 2 D CNN model for regression
model= Sequential()
model.add(Conv2D(32,kernel_size=(3,3),padding='same',activation='relu',input_shape=(x_train.shape[1],x_train.shape[2],1)))
model.add(Conv2D(64,kernel_size=(3,3),padding='same',activation='relu'))
model.add(MaxPooling2D(pool_size=(4,4)))
model.add(Dropout(0.25))
model.add(Dense(128,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='sigmoid'))
model.add(Dense(2, activation='sigmoid'))
model.summary()
#compile the model
model.compile(optimizer='ADADELTA', loss='binary_crossentropy', metrics=['accuracy'])
#train the model
model.fit(x_train, y_train, batch_size=1, epochs=1, verbose=2)
There are two problems in your approach:您的方法有两个问题:
model.add(Flatten())
after model.add(Dropout(0.25))
and before model.add(Dense(128,activation='relu'))
. model.add(Flatten())
after model.add(Dropout(0.25))
and before model.add(Dense(128,activation='relu'))
。binary_crossentropy
as the loss function, for this to work, you should keep your targets as they are ( 0
and 1
) and not use y_train = keras.utils.to_categorical(y_train,2)
.binary_crossentropy
作为损失 function,为此,您应该保持目标原样( 0
和1
),而不是使用y_train = keras.utils.to_categorical(y_train,2)
。 Your final layer should have 1
neuron and not 2
(Change model.add(Dense(2, activation='sigmoid'))
into model.add(Dense(1, activation='sigmoid'))
)1
神经元而不是2
( model.add(Dense(2, activation='sigmoid'))
更改为model.add(Dense(1, activation='sigmoid'))
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.