错误-'linear_regresion'对象不可迭代

问题描述 投票:0回答:1

我试图自行建立线性回归模型。编译器向我显示类型错误:“ linear_regression”不可迭代。这是我的代码:

from skrypt_3 import multab, sqrtab
import math, statistics

class linear_regresion:
    is_fitted = False

    def fit(x, y, self):
        print('learning has started')
        bg = len(list(x)) * sum(multab(x, y)) - sum(x) * sum(y)
        bd =  len(list(y)) * sum(sqrtab(x)) - math.sqrt(sum(x))
        b = bg / bd
        a = statistics.mean(y) - b * statistics.mean(x)
        is_fitted = True

    def predict(a, self):
        if is_fitted == True:
            return a + b * x
        else:
            return "model has not been fitted!"



c = [3, 3, 2, 4, 1]
d = [20, 25, 20, 30, 10]
xyz = linear_regresion()
xyz.fit(c, d)
print(xyz.predict(5))

还有我使用的两个功能:

def multab(x, y):
    op = []
    for n in range(len(x)):
        op.append(x[n] * y[n])
    return op

def sqrtab(x):
    op = []
    for n in range(len(x)):
        op.append(x[n] / x[n])
    return op
python iterable
1个回答
-1
投票

您的self的顺序错误。当您调用fit时,x是您的类的实例,它是不可迭代的。应该是:

import math, statistics

class linear_regresion:
    is_fitted = False

    def fit(self, x, y):
        print('learning has started')
        bg = len(list(x)) * sum(multab(x, y)) - sum(x) * sum(y)
        bd =  len(list(y)) * sum(sqrtab(x)) - math.sqrt(sum(x))
        b = bg / bd
        a = statistics.mean(y) - b * statistics.mean(x)
        is_fitted = True

    def predict(self, a):
        if is_fitted == True:
            return a + b * x
        else:
            return "model has not been fitted!"



c = [3, 3, 2, 4, 1]
d = [20, 25, 20, 30, 10]
xyz = linear_regresion()
xyz.fit(c, d)
print(xyz.predict(5))
© www.soinside.com 2019 - 2024. All rights reserved.