迭代每个 csv 列并使用线性回归预测值

Iterate every csv column and predict value using linear regression

我正在使用循环从每个 csv 行中获取值,然后 运行 通过 linear_regression_model 进行预测。需要的输出是,对于csv中的每一行,通过模型打印运行的预测值,如:

4.500
4.256
3.909
4.565
...
4.433

这是我所做的:

def prediction_loop():
    for index, row in ml_sample.iterrows():
        print(row['column'])
        new_data = OrderedDict(['column', row])
        new_data = pd.Series(new_data).values.reshape(1,-1)
        print(linear_regression_model.predict(new_data))

我得到的实际输出是:

Traceback (most recent call last):
new_data = OrderedDict(['column', row])
ValueError: too many values to unpack (expected 2)

在 csv 中有 87 行和 1 列。 如何优化代码? 谢谢

如果我对问题的理解正确,那么无需任何外部模块的帮助就可以非常有效地完成此操作。我们只需要一个简单的 class 来管理统计数据。假设输入文件每行包含一个数值,并且这些值是 Y,隐含的行号是 X。试试这个:-

class Stats():
    def __init__(self):
        self.n = 0
        self.sx = 0
        self.sy = 0
        self.sxx = 0
        self.syy = 0
        self.sxy = 0

    def add(self, x, y):
        self.sx += x
        self.sy += y
        self.sxx += x * x
        self.syy += y * y
        self.sxy += x * y
        self.n += 1

    def r(self):  # correlation coefficient
        return (self.n * self.sxy - self.sx * self.sy) / ((self.n * self.sxx - self.sx * self.sx) * (self.n * self.syy - self.sy * self.sy)) ** 0.5

    def b(self):  # slope
        return (self.n * self.sxy - self.sx * self.sy) / (self.n * self.sxx - self.sx * self.sx)

    def a(self):  # intercept
        return self.my() - self.b() * self.mx()

    def mx(self):  # mean x
        assert self.n > 0
        return self.sx / self.n

    def my(self):  # mean y
        assert self.n > 0
        return self.sy / self.n

    def y(self, x):  # estimate of y for given x
        return x * self.b() + self.a()


stats = Stats()

with open('lr.txt') as data:
    for i, line in enumerate(data):
        stats.add(i, float(line.split()[0]))

print(f'r={stats.r():.4f} slope={stats.b():.4f} intercept={stats.a():.4f}')

for x in range(stats.n):
    print(f'Estimate for {x} = {stats.y(x):.2f}')