机器学习的新手
我正在尝试使用accuracy score
找出线性模型的accuracy_score(y_test,y_pred)
。两个变量都已定义。但是出现错误
“未定义名称'y_test'”。
有人可以帮我吗? 变量的定义如下:
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=123)
y_pred = linreg.predict(X_test)
详细错误消息。 NameError跟踪(最近一次通话) 在()中 1#用于检查准确性和详细信息 2从sklearn.metrics导入precision_score ----> 3 precision_score(y_test,y_pred)
NameError:名称'y_test'未定义
在这里保存代码...
#creating a function for models
from sklearn.model_selection import train_test_split
from sklearn import metrics
#function
def train_test_rmse(x,y):
x = Iris_data[x]
y = Iris_data[y]
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_pred = linreg.predict(X_test)
return np.sqrt(metrics.mean_squared_error(y_test, y_pred))
print(train_test_rmse(['Sepal.Length'],['Sepal.Width']))
print(train_test_rmse(['Petal.Length'],['Sepal.Width']))
print(train_test_rmse(['Sepal.Length'],['Petal.Width']))
print(train_test_rmse(['Petal.Length'],['Petal.Width'])) #this one has least rmse
print(train_test_rmse(['Sepal.Width'],['Sepal.Length']))
print(train_test_rmse(['Petal.Width'],['Sepal.Width']))
#for checking the accuracy and details
from sklearn.metrics import accuracy_score
accuracy_score(y_test,y_pred)
答案 0 :(得分:2)
您已定义:
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.2,random_state=123)
在train_test_rmse()
函数内部。这就是为什么这些变量(y_test
和y_pred
)的作用域仅在函数内部的原因。
不能在函数外部使用它们。
使用以下代码:
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import accuracy_score
#function
def train_test_rmse(x,y):
x = Iris_data[x]
y = Iris_data[y]
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_pred = linreg.predict(X_test)
print(accuracy_score(y_test, y_pred)) # or you can save it in variable and return it
return np.sqrt(metrics.mean_squared_error(y_test, y_pred))