from __future__ import print_function
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras import backend as K
def sacc(y_true, y_pred):
return K.mean(K.equal(K.round(y_true), K.round(y_pred)))
batch_size = 256
epochs = 10000
img_rows, img_cols, channels = 32, 32, 3 # input image dimensions
if K.image_data_format() == 'channels_first':
X_train = X_train.reshape(X_train.shape[0], channels, img_rows, img_cols)
X_val = X_val.reshape(X_val.shape[0], channels, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], channels, img_rows, img_cols)
input_shape = (channels, img_rows, img_cols)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, channels)
X_val = X_val.reshape(X_val.shape[0], img_rows, img_cols, channels)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, channels)
input_shape = (img_rows, img_cols, channels)
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
model = Sequential()
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same', input_shape=input_shape))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(BatchNormalization())
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.compile(loss=keras.losses.mean_squared_error, optimizer=keras.optimizers.Adadelta(), metrics=[sacc])
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(X_val, y_val))
score = model.evaluate(X_val, y_val, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
我有一个Keras模型,最后一层是回归而不是softmax。我试图预测给定图像的分数(0.0到100.0)。我遇到的问题是需要训练超过10000个epochs,并且MSE下降非常缓慢。这是否符合预期,还是我的代码有问题?欢迎任何技巧或意见。
sgd
、adam
或者rmsprop
,它们可能比Adadelta
更快地收敛。 - DJKoptimizer = Adam(lr=0.001)
-- 更高的学习率可以加快训练速度,但可能过高并且简单地“错过重点”,导致结果发散。 - Daniel Möller