GridSearchCV用于神经元的数量

时间:2017-10-29 15:50:46

标签: python neural-network keras grid-search

我正在努力学习如何在基本的多层神经网络中网格搜索神经元的数量。我正在使用Python的GridSearchCV和KerasClasifier以及Keras。下面的代码非常适用于其他数据集,但由于某些原因我无法使其适用于Iris数据集,我找不到原因,我在这里错过了一些东西。我得到的结果是:

Best: 0.000000 using {'n_neurons': 3} 0.000000 (0.000000) with: {'n_neurons': 3} 0.000000 (0.000000) with: {'n_neurons': 5}

from pandas import read_csv

import numpy
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler

from keras.wrappers.scikit_learn import KerasClassifier
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
from sklearn.model_selection import GridSearchCV

dataframe=read_csv("iris.csv", header=None)
dataset=dataframe.values
X=dataset[:,0:4].astype(float)
Y=dataset[:,4]

seed=7
numpy.random.seed(seed)

#encode class values as integers
encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)

#one-hot encoding
dummy_y = np_utils.to_categorical(encoded_Y)

#scale the data
scaler = StandardScaler()
X = scaler.fit_transform(X)

def create_model(n_neurons=1):
    #create model
    model = Sequential()
    model.add(Dense(n_neurons, input_dim=X.shape[1], activation='relu')) # hidden layer
    model.add(Dense(3, activation='softmax')) # output layer
    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

model = KerasClassifier(build_fn=create_model, epochs=100, batch_size=10, initial_epoch=0, verbose=0)
# define the grid search parameters
neurons=[3, 5]

#this does 3-fold classification. One can change k. 
param_grid = dict(n_neurons=neurons)
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1)
grid_result = grid.fit(X, dummy_y)
# summarize results
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))

出于说明和计算效率的目的,我只搜索两个值。我真诚地为提出这么简单的问题而道歉。我是新手Python,从R切换,顺便说一句,因为我意识到深度学习社区正在使用python。

1 个答案:

答案 0 :(得分:1)

哈哈,这可能是我在Stack Overflow上遇到的最有趣的事情:)检查:

grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=5)

你应该看到不同的行为。您的模型获得完美分数的原因(cross_entropy 0的{​​{1}}相当于最佳模型)是因为您没有对数据进行洗牌,因为Iris包含三个平衡类每个Feed都有一个类似目标的类:

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 (first fold ends here) 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 (second fold ends here)2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]

这些问题很容易被每个模型解决 - 所以这就是你完美匹配的原因。

尝试在之前对数据进行随机播放 - 这应该会产生预期的行为。