我正在使用一个循环来从每个CSV行中获取值,并通过linear_regression_model进行预测。所需的输出是,对于CSV中的每一行,打印通过模型预测的值,如:
4.5004.2563.9094.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列。我如何优化代码?谢谢
回答:
如果我正确理解了问题,那么这可以非常高效地完成,而不需要任何外部模块的帮助。我们只需要一个简单的类来管理统计数据。假设是输入文件每行包含一个数值,这些值是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): # 相关系数 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): # 斜率 return (self.n * self.sxy - self.sx * self.sy) / (self.n * self.sxx - self.sx * self.sx) def a(self): # 截距 return self.my() - self.b() * self.mx() def mx(self): # 平均x assert self.n > 0 return self.sx / self.n def my(self): # 平均y assert self.n > 0 return self.sy / self.n def y(self, x): # 对于给定的x估计y 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}')