我正在尝试按照此reference使用Sklearn中的GridSearchCV来查找Keras神经网络的最佳超参数。 这是我写的代码:
import numpy as np
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.metrics import mean_squared_error
from math import sqrt
from sklearn.model_selection import ShuffleSplit
def create_model():
model=Sequential()
model.add(Dense(18, input_dim=18, activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(1))
model.compile(loss=mean_squared_error, optimizer='adam')
return model
x_train=np.load('x_train.npy')
y_train=np.load('y_train.npy')
x_dev=np.load('x_dev.npy')
y_dev=np.load('y_dev.npy')
model=KerasRegressor(build_fn=create_model, verbose=0)
batch_size1=np.arange(32, 1024, 100)
epochs1=np.arange(10, 100, 40)
param_grid=dict(batch_size=batch_size1, epochs=epochs1)
cv = ShuffleSplit(n_splits=3, test_size=0.01, random_state=0)
grid=GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=1, cv=cv)
grid_result=grid.fit(x_train, y_train)
print("Best: %f using %s" % (grid_result.best_score_,
grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
print("%f (%f) with: %r" % (mean, stdev, param))
我收到以下错误: ValueError:使用序列设置数组元素。 error message, photo 1 error message, photo 2 据我所知link,问题是由于以下两个原因之一造成的: 1-数据和标签的长度不同。 2-对于特定的特征向量,元素的数量不相等。 但我很确定我的数据标记正确,我可以在同一数据集上应用简单的sklearn和keras模型,没有任何问题。 那么,这个错误的原因可能是什么?
答案 0 :(得分:0)
您正在尝试将keras损失设置为sklearn函数。尝试将其设置为字符串。
model.compile(loss='mean_squared_error', optimizer='adam')