简体   繁体   English

我不断收到错误名称'y_test'未定义

[英]I keep on getting the error name 'y_test' is not defined

I really need your help: I've written this code:我真的需要你的帮助:我写了这段代码:

from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import accuracy_score

def train_test_rmse(x,y):
    X = df_new[feature_cols]
    y = df_new['TOTAL CONSTRUCTION COST - EXCLUDING TAX']
    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.2,random_state=123)
    linreg = LinearRegression()
    linreg.fit(X_train, y_train)
    y_test = train_test_split(x, y, test_size = 0.2,random_state=123)
    y_pred = linreg.predict(X_test)
    print(accuracy_score(y_test, y_pred))  
    return np.sqrt(metrics.mean_squared_error(y_test, y_pred)) 

^ The code above runs correctly. ^ 上面的代码运行正确。 But when I try to plot a scatter plot in the cell beneath:但是当我尝试在下面的单元格中 plot 分散 plot 时:

import matplotlib.pyplot as plt
plt.scatter(y_test, y_pred)
plt.xlabel('Actual Y')
plt.ylabel('Predicted Y')
plt.show()

I get the error "name 'y_test' is not defined".我收到错误“名称'y_test'未定义”。 Please let me know how to fix it.请让我知道如何解决它。 Thanks.谢谢。

In the code, i see that y_test is defined inside the train_test_rmse function, you need to initialize y_test outside this function.在代码中,我看到y_test是在train_test_rmse function 中定义的,您需要在此 function 之外初始化y_test

your code should work fine with few changes as follows:您的代码应该可以正常工作,只需进行一些更改,如下所示:

y_test = None

def train_test_rmse(x,y):
  
  global y_test
  
    X = df_new[feature_cols]
    y = df_new['TOTAL CONSTRUCTION COST - EXCLUDING TAX']
    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.2,random_state=123)

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

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