参加数学建模会用到统计学的知识解决单一因素与多变量之间的关系,也多用线性回归的知识,书上讲解主要用matlab去做,但主要还是自己懒,短期内不想再去学习,于是尝试用python中的模块取模拟,但是好像sklearn中不带有置信区间,想用的话得自己实现,反正也不太懂置信区间,就直接干吧。
'''
线性回归
'''
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
class Linear(object):
def __init__(self, x):
self.x = x
self.lenth = len(x)
return None
def create_data(self):
self.y = self.x*3 + 5.3 + np.random.randn(self.lenth)
return self.y
def plot_data(self, x_test=None, y_hat=None, c='r'):
plt.figure(figsize=(12, 9))
plt.scatter(self.x, self.y, c='b', label='original')
if type(y_hat) != None:
plt.scatter(x_test, y_hat, c=c, label='predict')
plt.ylim(0)
plt.legend()
plt.show()
return None
def model(self):
self.linear = LinearRegression(fit_intercept=True)
self.linear.fit(self.x.reshape(-1, 1), self.y)
return None
def predict(self, x_test):
return self.linear.predict(x_test)
def coef_intercept(self):
print('线性回归的回归系数:', self.linear.coef_)
print('线性回归的截距:', self.linear.intercept_)
return None
if __name__ == '__main__':
x = np.arange(20)
temp = Linear(x)
y = temp.create_data()
temp.model()
y_hat = temp.predict(x.reshape(-1, 1))
temp.plot_data(x, y_hat)
temp.coef_intercept()
第一次写面向对象的代码,感觉运行起来好像也没什么bug。如果有错误希望以后再看能找到吧。