总是说我x没有被定义

来源:5-3 简单线性回归的实现

慕工程7471586

2020-04-14

我每次修改都会重新在notebook上重新执行import及后续语句,但每次都抱有同样的错误
怎么回事,多谢

import numpy as np

class SimpleLinearRegression:
def init(self):
self.a_ = None
self.b_ = None

def fit(self, x_train, y_train):
    assert x_train.ndim == 1, \
        "Simple Linear Regressor can only solve single feature training data"
    assert len(x_train) == len(y_train), \
        "the size of x_train must be equal to the size of y_train"
    x_mean = np.mean(x_train)
    y_mean = np.mean(y_train)
    num = 0.0
    d = 0.0
    for x, y in zip(x_train, y_train):
        num += (x - x_mean) * (y - y_mean)
        d += (x - x_mean) ** 2
    self.a_ = num / d
    self.b_ = y_mean - self.a_ * x_mean
    return self

def predict(self, x_predict):
    return np.array([self._predict(x) for x in x_predict])

def _predict(self, x_single):
    return self.a_ * x_single + self.b_

NameError Traceback (most recent call last)
in
----> 1 req.fit(x,y)

~\Desktop\ML\pycharmtest\SimpleLinearRegeression.py in fit(self, x_train, y_train)
10 assert x_train.ndim == 1,
11 “Simple Linear Regressor can only solve single feature training data”
—> 12 assert len(x_train) == len(y_train),
13 "the size of x_train must be equal to the size of y_train"
14 x_mean = np.mean(x_train)

NameError: name ‘x’ is not defined

1

写回答

1回答

liuyubobobo

2020-04-15

根据你的这个报错,先不说 x 的问题,你的 fit 里的两个 assert 没有通过。也就是你传的 x_train, y_train 参数,没有满足:

x_train.ndim == 1

len(x_train) == len(y_train)


不要只看 py 文件,也看一下 Jupyter Notebook 中的代码有没有问题?


==========


这个课程的所有代码,都可以在慕课网的源码下载区下载,可以尝试将课程的官方代码下载下载,在你的环境下运行,看是否有同样的问题?如果没有问题,请仔细调试比对,看看自己的代码哪里不一样?哪里有问题?


本小节课程官方代码:https://git.imooc.com/coding-169/coding-169/src/master/05-Linear-Regression/03-Simple-Linear-Regression-Implementation


继续加油!:)


0
0

Python3入门机器学习 经典算法与应用  

Python3+sklearn,兼顾原理、算法底层实现和框架使用。

5839 学习 · 2437 问题

查看课程