首页 > 解决方案 > 迭代每个 csv 列并使用线性回归预测值

问题描述

我正在使用一个循环从每个 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 列。如何优化代码?谢谢

标签: pythonloopscsvmachine-learninglinear-regression

解决方案


如果我正确理解了这个问题,那么这可以在没有任何外部模块的帮助下非常有效地完成。我们只需要一个简单的类来管理统计信息。假设输入文件每行包含一个数值,并且这些值是 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}')

推荐阅读