import numpy as np 输入数据 pmhours = np.arange(1, 12+1) # p.m.时间 pmtemps = np.array([66,…
- User
import numpy as np
输入数据
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(23): 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], '.', 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 39, in plt.plot(hours[i], temps[i], 'o', color='c') # 绘制原始数据点 NameError: name 'plt' is not defined
- Assistant
在代码开头添加以下导入语句即可解决错误:
import matplotlib.pyplot as plt