'''
最小二乘法求解线性回归
'''
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
#防止中文乱码
plt.rcParams['font.sans-serif']=[u'simHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
#加载数据
path = '../datas/household_power_consumption_200.txt'
#csv默认分隔符为',',这里以 ; 分割
df = pd.read_csv(filepath_or_buffer=path,sep=';',low_memory=False)
# 查看info信息 批量注释 Ctrl+/
# print(df.info())
# print(df.head(5))
'''
获取功率值为属性特征X,获取电流值为特征Y
'''
X = df.iloc[:,2:4]
Y = df.iloc[:,5]
# print(X.head(5))
# print(Y.head(5))
#将数据分为训练集和数据集
# random_state 随机数种子 保证多次执行的时候 切分完的数据一致
x_train,x_test,y_train,y_test = train_test_split(X,Y,train_size=0.7,test_size=0.3,random_state=28)
print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
#模型构建
# 1.使用numpy的API将DataFrame转换为矩阵形式 将x_train y_train 由DataFrame转为矩阵 然后进行矩阵计算
x = np.mat(x_train)
y = np.mat(y_train).reshape(-1,1)
print(x.shape)
print(y.shape)
# 2 求解析式
theta = (x.T * x).I * x.T * y
print(theta)
# 3.使用模型对数据做预测
y_hat = np.mat(x_test)*theta
#画图看下效果
t = np.arange(len(x_test))
plt.figure(facecolor='w')
plt.plot(t,y_test,'r-',linewidth=2,label = u'真实值')
plt.plot(t,y_hat,'g-',linewidth=2,label = u'预测值')
plt.legend(loc = 'lower right') #设置label
plt.title("线性回归")
plt.show()
最终打印如图 此处不考虑效果,仅实现