名称错误:未定义名称“x_train”

2024-04-19 20:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的,但有人能告诉我怎么了吗?实际上,我正在尝试根据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)

Tags: csv数据testimportmodelasnptrain
1条回答
网友
1楼 · 发布于 2024-04-19 20:29:14

在定义变量之前,需要使用变量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 |
#  +------------------------------------------+

相关问题 更多 >