【问题标题】:NameError: name 'x_train' is not definedNameError:名称“x_train”未定义
【发布时间】:2017-06-09 03:33:41
【问题描述】:

我是新手,但谁能告诉我有什么问题吗?我实际上是在尝试根据我在 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)

【问题讨论】:

  • 很明显,在这里x_train = np.array(x_train).reshape(len(x_train), -1) 您正在尝试使用x_train,它尚未在x_train 分配中声明。这是不允许的
  • 在将 x_train 用作参数之前缺少声明:x_train = np.array(x_train).reshape(len(x_train), -1)
  • 您错过了第 6 行和第 7 行之间的一行,它将 df 拆分为 x_train 和 x_test。类似x_train, x_test = ...

标签: python numpy matplotlib machine-learning scikit-learn


【解决方案1】:

在定义变量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 |
#  +------------------------------------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2021-04-15
    • 2019-01-26
    • 2021-10-05
    相关资源
    最近更新 更多