为啥我得到 AttributeError:'KerasClassifier' 对象没有属性 'model'?

Posted

技术标签:

【中文标题】为啥我得到 AttributeError:\'KerasClassifier\' 对象没有属性 \'model\'?【英文标题】:Why am i getting AttributeError: 'KerasClassifier' object has no attribute 'model'?为什么我得到 AttributeError:'KerasClassifier' 对象没有属性 'model'? 【发布时间】:2017-11-21 05:09:39 【问题描述】:

这是代码,我只在最后一行遇到错误,即y_pred = classifier.predict(X_test)。我得到的错误是AttributeError: 'KerasClassifier' object has no attribute 'model'

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import datasets
from sklearn import preprocessing
from keras.utils import np_utils

# Importing the dataset
dataset = pd.read_csv('Data1.csv',encoding = "cp1252")
X = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, -1].values

# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_0 = LabelEncoder()
X[:, 0] = labelencoder_X_0.fit_transform(X[:, 0])
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
labelencoder_X_3 = LabelEncoder()
X[:, 3] = labelencoder_X_3.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

# Creating the ANN!
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
def build_classifier():
    # Initialising the ANN
    classifier = Sequential()
    # Adding the input layer and the first hidden layer
    classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 10))

    classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))

    classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
    classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
    return classifier

classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 2)
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 1, n_jobs=1)
mean = accuracies.mean()
variance = accuracies.std()

# Predicting the Test set results
import sklearn
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Predicting new observations
test = pd.read_csv('test.csv',encoding = "cp1252")
test = test.iloc[:, 1:].values
test[:, 0] = labelencoder_X_0.transform(test[:, 0])
test[:, 1] = labelencoder_X_1.transform(test[:, 1])
test[:, 2] = labelencoder_X_2.transform(test[:, 2])
test[:, 3] = labelencoder_X_3.transform(test[:, 3])
test = onehotencoder.transform(test).toarray()
test = test[:, 1:]
new_prediction = classifier.predict_classes(sc.transform(test))
new_prediction1 = (new_prediction > 0.5)

【问题讨论】:

【参考方案1】:

您收到错误是因为您实际上并没有从 KerasClassifier 训练返回的模型,这是一个 Scikit-learn 包装器以利用 Scikit-learn 函数。

例如,您可以执行 GridSearch(您可能知道,因为代码似乎来自 Udemy ML/DL 课程):

def build_classifier(optimizer):
    classifier = Sequential()
    classifier.add(Dense(units = 6, kernel_initializer = 'uniform', 
        activation = 'relu', input_dim = 11))
    classifier.add(Dense(units = 6, kernel_initializer = 'uniform', 
        activation = 'relu'))
    classifier.add(Dense(units = 1, kernel_initializer = 'uniform', 
        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': [100, 500],
          'optimizer': ['adam', 'rmsprop']
grid_search = GridSearchCV(estimator = classifier,
                       param_grid = parameters,
                       scoring = 'accuracy',
                       cv = 10)
grid_search = grid_search.fit(X_train, y_train)

如果您不需要 Scikit-learn 功能,我建议您避免使用包装器并简单地使用以下方式构建您的模型:

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
…

然后训练:

model.fit( … )

【讨论】:

【参考方案2】:

因为您还没有安装classifier。要让classifier 使用模型变量,您需要调用

classifier.fit(X_train, y_train)

虽然你在classifier 上使用了cross_val_score(),并且发现了准确性,但这里要注意的主要一点是cross_val_score 将克隆提供的模型并将它们用于交叉验证折叠。因此,您的原始估算器 classifier 未受影响且未经训练。

你可以在我的另一个answer here看到cross_val_score的工作

所以把上面提到的行放在y_pred = classifier.predict(X_test) 行的上方,你就准备好了。希望这说明清楚。

【讨论】:

以上是关于为啥我得到 AttributeError:'KerasClassifier' 对象没有属性 'model'?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我得到 AttributeError: Object has no attribute? [关闭]

为啥我得到 AttributeError: Object has no attribute? [关闭]

为啥我得到 AttributeError:'LinearRegressionGD' 对象没有属性 'n_iter'

继承人一些异步代码为亚马逊搜索提供硒队列,为啥我得到 AttributeError? __init__ 没有运行?

为啥keras安装以后导入失败?

AttributeError:“张量”对象没有属性“to_sparse”