Keras:用于超参数调整的GridSearchCV

时间:2017-06-24 16:07:03

标签: python tensorflow deep-learning keras

我目前正在训练CNN对波浪进行分类。虽然代码完美无缺,但用于超参数调优的GridSearchCV无法按预期工作。我很困惑,因为我使用类似的代码来调整MLP中的超参数,它就像一个魅力。这是完整的代码,顺便说一下,我使用TF作为后端。

import pandas as pd
import numpy as np

#Import training set
training_set = pd.read_csv("training_set.csv", delimiter=";")
X_train = training_set.iloc[:,1:].values
y_train = training_set.iloc[:,0:1].values

#Import test set
test_set = pd.read_csv("test_set_v2.csv", delimiter=";")
X_test = test_set.iloc[:,1:].values
y_test = test_set.iloc[:,0:1].values

from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.fit_transform(X_test)

#Convert X into 3D tensor
X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))
X_test = np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))

#Importing the CNN libraries
from keras.models import Sequential
from keras.layers import Conv1D,MaxPooling1D,Flatten
from keras.layers import Dropout,Dense
from keras.layers.normalization import BatchNormalization

#Parameter tuning
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
def build_classifier(optimizer, dropout1, dropout2):
    classifier = Sequential()
    classifier.add(Conv1D(filters=4,kernel_size=4,activation='relu',input_shape=(X_train.shape[1],1)))
    classifier.add(MaxPooling1D(strides=4))
    classifier.add(BatchNormalization())    
    classifier.add(Flatten())
    classifier.add(Dropout(0.25))
    classifier.add(Dense(8, activation='relu'))
    classifier.add(Dropout(0.25))
    classifier.add(Dense(1,activation='sigmoid'))
    classifier.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
    return classifier

classifier = KerasClassifier(build_fn=build_classifier)

parameters = {'batch_size': [25,32],
              'epochs': [5,10],
              'optimizer': ['adam', 'rmsprop'],
              'dropout1' : [0.2,0.25,3],
              'dropout2' : [0.2,0.25,3],
              }
grid_search = GridSearchCV(estimator=classifier,
                           param_grid = parameters,
                           scoring = 'accuracy',
                           cv = 10)
grid_search = grid_search.fit(X_train, y_train)
best_parameters = grid_search.best_params_
best_accuracy = grid_search.best_score_

奇怪的是,它完美地运行了一个时代然后它引发了以下错误。

  

文件“C:\ Program Files \ Anaconda3 \ lib \ site->> packages \ keras \ wrappers \ scikit_learn.py”,第220行,预测      return self.classes_ [classes]

     

IndexError:索引1超出轴0的大小为1

有人可以帮助我吗?非常感谢任何形式的帮助!非常感谢你们!

1 个答案:

答案 0 :(得分:0)

解决

通过github master分支更新