import numpy as np import matplotlib.pyplot as plt 输入数据 pmhours = np.arange(1, 12+1) #…
- User
import numpy as np import matplotlib.pyplot as plt
输入数据
pm_hours = np.arange(1, 12+1) # p.m.时间 pm_temps = np.array([66, 66, 65, 64, 63, 63, 62, 61, 60, 60, 59, 58]) # p.m.温度 am_hours = np.arange(1, 11+1) # a.m.时间 am_temps = np.array([58, 58, 58, 58, 57, 57, 57, 58, 60, 64, 67, 68]) # a.m.温度
拼接数据
hours = np.concatenate([pm_hours, am_hours]) temps = np.concatenate([pm_temps, am_temps])
构造矩阵A和向量b
A = np.ones([24, 4]) for i in range(24): A[i][1] = hours[i] A[i][2] = hours[i] ** 2 A[i][3] = hours[i] ** 3 b = temps.reshape([24, 1])
计算最小二乘解
ATA = np.dot(A.T, A) ATb = np.dot(A.T, b) x = np.linalg.solve(ATA, ATb)
打印拟合结果
print('拟合结果为 y = {:.2f} + {:.2f}x + {:.2f}x^2 + {:.2f}x^3'.format( x[0][0], x[1][0], x[2][0], x[3][0]))
绘制曲线
hours_for_plot = np.linspace(1, 11+12/24, 100) # 生成绘图用的时间序列 temps_for_plot = x[0][0] + x[1][0]*hours_for_plot + x[2][0] *
hours_for_plot2 + x[3][0]*hours_for_plot3 # 计算拟合值 for i in range(24): if i < 12: c = 'r' # 红色表示p.m.时间 else: c = 'b' # 蓝色表示a.m.时间 plt.plot(hours[i], temps[i], 'o', color='c') # 绘制原始数据点 plt.plot(hours_for_plot, temps_for_plot, color='g') # 绘制拟合曲线 plt.xlabel('Hours') plt.ylabel('Temperature') plt.show() plt.savefig('zuixiaoercheng1.png')Traceback (most recent call last): File "/home/lurenmax/work/liyunxuan/shiyan3/zuixiaoercheng.py", line 17, in A[i][1] = hours[i] IndexError: index 23 is out of bounds for axis 0 with size 23 ➜ work
- Assistant
在第17行中,代码使用了一个循环遍历数组并赋值,但是数组的大小不够,最后一个元素下标为23但是数组只有23个元素,因此越界了。解决方案是将该循环改为遍历两个时间序列的并集,例如:
for i in range(len(hours)): A[i][1] = hours[i] A[i][2] = hours[i] ** 2 A[i][3] = hours[i] ** 3 if i < 12: b[i][0] = pm_temps[i] else: b[i][0] = am_temps[i-12]