库艾尼奥 2019-01-26 11:11 采纳率: 0%
浏览 1591

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

图片说明

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-09 17:33
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

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

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿