简体   繁体   English

Python中赋值错误之前引用的局部变量

[英]Local variable referenced before assignment error in Python

I'm trying to find the bias of the data.我试图找到数据的偏差。 But I'm struck by the following error.但我对以下错误感到震惊。 Can you help me out?你能帮我吗?

My code is我的代码是

total_bias = 0
error = [0]*len(y_train)
def bias(train_label , predicted_label):
    for i in range(0,len(train_label)):
        error[i] = train_label[i]-predicted_label[i]
        total_bias+=error[i]
        print("Bias of the data is\n",total_bias)

So, when I called that function I got the error as follows因此,当我调用该函数时,出现如下错误

UnboundLocalError                         Traceback (most recent call last)
<ipython-input-116-bd69154610c9> in <module>
----> 1 bias(y_train , y_train_pred )

<ipython-input-115-9efa292295d6> in bias(train_label, predicted_label)
  4     for i in range(0,len(train_label)):
  5         error[i] = train_label[i]-predicted_label[i]
  ----> 6         total_bias+=error[i]
  7         print("Bias of the data is\n",total_bias)

 UnboundLocalError: local variable 'total_bias' referenced before assignment

Just change you code like that so that total_bias is seen as global只需更改您的代码,以便将 total_bias 视为global

total_bias = 0
error = [0]*len(y_train)

def bias(train_label, predicted_label):
    global total_bias #has to be defined global, otherwise it is seen as in a local scope
    for i in range(0,len(train_label)):
        error[i] = train_label[i] - predicted_label[i]
        total_bias += error[i]
        print("Bias of the Data is \n",total_bias)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM