1、用sklearn.linear_model包中的LinearRegression对表3-1所示的示例进行线性回归实验,比较结果。
| 温度/℃ | 15 | 20 | 25 | 30 | 35 | 40 |
| 小花数量/朵 | 136 | 140 | 155 | 160 | 157 | 175 |
import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression #plt.axis([0, 50, 0, 300]) data = np.array([[15,136], [20,140],[25,155], [30,160], [35,157], [40,175]], np.int32) x = data[:,0:-1]#从第0列开始到倒数第2列停止 y = data[:,-1] #取出最后一列 print(np.shape(x), np.shape(y)) model = LinearRegression().fit(x,y) print(model.predict([[169]])) #注意model.predict()中要预测的数据跟训练数据x的shape保持一致 print(model.coef_)#coef_:回归系数(斜率) print(model.intercept_)#intercept_:截距项 print(model.score(x,y))# 返回预测的决定系数R^2; plt.scatter(x,y) plt.plot(x, model.predict(x)) plt.show()
- 写出用迭代法求解方程的迭代关系式。
import math #def f(x): x=0 for i in range(50): x=(x**5+x**4+(math.e**x)+1)/11 print(str(i)+":"+str(x))



