簡體   English   中英

Scikit-learn cross_val_score 拋出 ValueError:必須始終傳遞“Layer.call”的第一個參數

[英]Scikit-learn cross_val_score throws ValueError: The first argument to `Layer.call` must always be passed

我正在做一個深度學習項目,我嘗試按照一個教程來評估我的 model 與交叉驗證。

我在看這個教程: https://machinelearningmastery.com/use-keras-deep-learning-models-scikit-learn-python/

我首先將我的數據集拆分為特征和標簽:

labels = dataset['Label']
features = dataset.loc[:, dataset.columns != 'Label'].astype('float64')

我有以下形狀:

features.shape ,labels.shape
((2425727, 78), (2425727,))

我使用 RobustScalar 來擴展我的數據以及我是如何擁有的

features
array([[ 1.40474359e+02, -1.08800488e-02,  0.00000000e+00, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [ 1.40958974e+02, -1.08609909e-02, -2.50000000e-01, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [ 1.40961538e+02, -1.08712390e-02, -2.50000000e-01, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       ...,
       [ 1.48589744e+02, -1.08658453e-02,  0.00000000e+00, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [-6.92307692e-02,  1.77654485e-01,  1.00000000e+00, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
       [-6.92307692e-02,  6.18858398e-03,  5.00000000e-01, ...,
         0.00000000e+00,  0.00000000e+00,  0.00000000e+00]])

labels
array([0, 0, 0, ..., 0, 0, 0])

現在數據已准備好執行交叉驗證。

from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score

# Function to create model, required for KerasClassifier
def create_model():
    # create model
    model= Sequential()
    model.add(Dense(128, activation='relu',input_shape = (78,1)))
    model.add(Dropout(0.01))
    model.add(Dense(15, activation='softmax'))

    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

#fix random seed for reproducibility
seed = 7
np.random.seed(seed)
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)

# create model
model = KerasClassifier(build_fn=create_model(), epochs=30, batch_size=64, verbose=0)

# evaluate using 5-fold cross-validation
results = cross_val_score(model, features, labels, cv=kfold,scoring='accuracy', error_score="raise")
print(results.mean())

執行此操作后,我收到此錯誤:“ValueError:必須始終傳遞Layer.call的第一個參數。”

我還檢查了 scikit learn 文檔以檢查我是否做錯了什么: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html

我還試圖尋找可能遇到此問題的其他人,例如: https://github.com/scikit-learn/scikit-learn/issues/18944

但我無法解決這個問題。 有人可以幫我嗎?

model = KerasClassifier(build_fn=create_model(), ...) 

嘗試刪除 function create_model 的大括號,因為參數期望回調 function 將在需要時調用。 所以會是

model = KerasClassifier(build_fn=create_model, ... ) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM