0 导入库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import optimize
1 定义方程形式
# 线性形式
def f_1(x, A, B):
return A + B*x
# 复合函数形式
def f_2(x, A, B):
return A * B**x
2 数据
x:病人住院的天数
y:是病人出院后长期恢复的预后指数(指数的数值越大表示预后的结局越好)
x = np.array([2, 5, 7, 10, 14, 19, 26, 31, 34, 38, 45, 52, 53, 60, 65]) # 住院天数
y = np.array([54, 60, 45, 37, 35, 25, 20, 15, 18, 13, 8, 11, 8, 4, 6]) # 预后指数
3 拟合方程
A1, B1 = optimize.curve_fit(f_1, x, y)[0]
A2, B2 = optimize.curve_fit(f_2, x, y)[0]
y1 = A1 + B1*x
y2 = A2 * B2**x
4 画图
from matplotlib.font_manager import FontProperties
font_set = FontProperties(fname=r"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", size=16)
def runplt():
plt.figure() # 定义figure
plt.title(u'对重伤病人出院后的长期恢复情况进行预测',fontproperties=font_set, size=20)
plt.xlabel(u'住院天数(day)',fontproperties=font_set)
plt.ylabel(u'预后指数',fontproperties=font_set)
plt.axis([0, 70, 0, 70]) # 坐标轴
plt.grid(True) # 网格线
return plt
plt = runplt()
plt.scatter(x, y, c='b', label='Data')
标准相关系数
非线性趋势
plt = runplt()
plt.scatter(x, y, c='b', label='Data')
plt.plot(x, y1, 'g-', label='Linear Regression')
plt.plot(x, y2, 'r:', label='Compound Regression')
plt.legend()
复合函数回归比线性回归拟合效果更好
5 计算残差
residual1 = y - y1 # 线性回归残差
residual2 = y - y2 # 复合函数回归残差
residual1
residual2
6 计算总平方和
# 线性回归残差平方和
sse1 = 0
for i in residual1:
sse1 += i**2
# 复合函数回归残差平方和
sse2 = 0
for i in residual2:
sse2 += i**2
sse1
sse2
常用的可转化成线性的非线性回归模型