机器学习:线性回归(最小二乘法代码)


'''
最小二乘法求解线性回归
'''
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()

最终打印如图  此处不考虑效果,仅实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值