NameError:未定义名称"x_train"

AwA*_*rAw 0 python numpy machine-learning matplotlib scikit-learn

我是新手,但任何人都可以告诉我它有什么不对吗?我实际上是在尝试根据excel中的数据进行预测分析(线性回归图).但是,我的图表没有绘制出来,我也遇到了这个错误.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy
from sklearn import linear_model
df = pd.read_csv("C:\MongoDB\MongoData.csv") 

x_train = np.array(x_train).reshape(len(x_train), -1)
x_train.shape
y_train= [1,2,3,4,5]
x_test = x_test.reshape(-1, 1)
x_test.shape

linear = linear_model.LinearRegression()

linear.fit(x_train, y_train)
linear.score(x_train, y_train)

print('Coefficient: \n', linear.coef_)
print('Intercept: \n', linear.intercept_)

predicted= linear.predict(x_test)
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 6

x_train在定义变量之前,可以使用变量两次.您需要先定义它,然后再使用它.

  x_train = np.array(x_train).reshape(len(x_train), -1)
# ^^^^^^^            ^^^^^^^              ^^^^^^^
#    |                  |                    |
#    |    +------------------------------------------------+
#    |    | You use x_train twice before it's ever defined |
#    |    +------------------------------------------------+
#  +------------------------------------------+
#  | Your first definition of x_train is here |
#  +------------------------------------------+
Run Code Online (Sandbox Code Playgroud)