简体   繁体   中英

Python: cannot train regression model in Keras

I am trying to train a DNN with Keras. The model is here defined:

model = Sequential()
model.add(Dense(2050, input_shape=(2050, 75), activation='relu'))
model.add(Dense(1024, activation='relu'))
model.add(Dense(1024, activation='relu'))
model.add(Dense(1024, activation='relu'))
model.add(Dense(75, activation='sigmoid'))

The cost function is the mse. The idea here is training with a set of 3000 images with size 2050*75, which basically are two different features extracted from a 1025*75 image, in order to get 3000 image with size 1025*75 in the output, which are some kind of representation of the original image.

So, the input is a (3000, 2050, 75) tensor, while the output dimension is (3000, 1025, 75).

I can see why Keras gives me the following error:

ValueError: Error when checking target: expected dense_5 to have shape (None, 2050, 75) but got array with shape (3000, 1025, 75)

There must be a way to avoid this error, maybe by redefining the DNN dimensions or layers. Do you have any suggestion? Thanks.

EDIT: As requested, this is the complete code.

X = train_set
Y = m
[n_samples, n_freq, n_time] = X.shape

model = Sequential()
model.add(Dense(n_freq, input_shape=(n_freq, n_time), activation='relu'))
model.add(Dense(n_hid, activation='relu'))
model.add(Dense(n_hid, activation='relu'))
model.add(Dense(n_hid, activation='relu'))
model.add(Dense(n_time, activation='sigmoid'))

model.summary()
model.compile(optimizer='rmsprop',loss='mse',metrics=['mae','accuracy'])
model.fit(np.abs(X), np.abs(Y), epochs=n_epochs, batch_size=batch_size)
score = model.evaluate(np.abs(X), np.abs(Y), batch_size = batch_size)

Since, you cannot reshape the array internally using the reshape layer, because total size of new array must be unchanged. I suggest to flat the tensor, using the flatten layer. But first, you need to reshape the y:

y = y.reshape(-1, 1025*75)

the updated model would look like this:

model = Sequential()
model.add(Dense(n_freq, input_shape=(n_freq, n_time), activation='relu'))
model.add(Dense(n_hid, activation='relu'))
model.add(Dense(n_hid, activation='relu'))
model.add(Dense(n_hid, activation='relu'))
model.add(Flatten())
model.add(Dense(1025*75, activation='sigmoid'))

model.summary()
model.compile(optimizer='rmsprop',loss='mse',metrics=['mae','accuracy'])
model.fit(np.abs(X), np.abs(y), epochs=n_epochs, batch_size=batch_size)
#score = model.evaluate(np.abs(X), np.abs(Y), batch_size = batch_size)

After, you can reshape you y_pred back to (-1,1015,75) shape:

y_pred = y_pred.reshape(-1,1015,75)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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