python 机器学习“local variable 'clf' referenced before assignment”。尝试过全局变量的方法。

【问题】:
在def CVKFold 后,输入变量测试反馈 :
“local variable 'clf' referenced before assignment”。

【代码如下】:

def CVKFold(k,X,y,Model): 
    np.random.seed(1)

    train_accuracy=[0 for i in range(k)]
    validation_accuracy=[0 for i in range(k)]   

    idx=0


    kf=KFold(n_splits=k,shuffle=True) 

    for train_index,test_index in kf.split(X):
        X_train,X_test=X.iloc[train_index],X.iloc[test_index]
        y_train,y_test=y.iloc[train_index],y.iloc[test_index]

        if model=='Logit':
            clf=LogisticRegression(random_state=0)

        if model=='RForest':
            clf=RandomForestClassifier(random_state=0)

        if model=='Tree':
            clf=DecisionTreeClassifier(random_state=0)

        clf.fit(X_train,y_train)
        y_train_pred=clf.predict(X_train)
        y_test_pred=clf.predict(X_test)

        train_accuracy[idx]=np.mean(y_train_pred==y_train)
        validation_accuracy[idx]=np.mean(y_test_pred==y_test)

        idx+=1

    print (train_accuracy[idx])
    print (validation_accuracy[idx])
    return train_accuracy,validation_accuracy

【输入变量】:

    train_acc,test_acc=CVKFold(5,all_x,y,'Logit')

【报错】:
UnboundLocalError Traceback (most recent call last)
in ()
----> 1 train_acc,test_acc=CVKFold(5,all_x,y,'Logit')

in CVKFold(k, X, y, Model)
24 clf=DecisionTreeClassifier(random_state=0)
25
---> 26 clf.fit(X_train,y_train)
27 y_train_pred=clf.predict(X_train)
28 y_test_pred=clf.predict(X_test)

UnboundLocalError: local variable 'clf' referenced before assignment

【尝试过】:
在最开始定义clf=DecisionTreeClassifier()
在for循环前加入global clf
但是输入变量后,不论k值如何变,均反馈0 0

图片说明

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^