import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#文件中含有一个变量与一个预测值
path='C:/Users/xpp/Desktop/data.txt'
data=pd.read_csv(path,header=None,names=['Population','Profit'])
data.head()
#可视化数据
data.plot(kind='scatter',x='Population',y='Profit',figsize=(12,8))
#读取数据,数据处理,在数据最前面添加一列常数,在计算时充当常数项
data.insert(0,'Ones',1)
#初始化X,y
cols=data.shape[1]#shape表示行列数,[0]行,[1]列
X=data.iloc[:,:-1]# 数据为二维数组,取所有的行,以及除了最后一列的所有列
y=data.iloc[:,cols-1:cols]# 同上,不过是只取最后一列
X.head()
# 因为X,y是一个DataFrame,所以要进行运算就要重新转换成矩阵
Xnp=np.array(X.values)
ynp=np.array(y.values)
theta=np.array([0,0]).reshape(1,2)#定义theta初始值为0,一行两列
#使用power函数计算代价函数J(theta)的值,X为一个矩阵
#计算公式为 J(theta)= (1/2m)* (theta0 + theta1*Xi - yi)i从1-m
def computeCost(X,y,theta):
# 在此数据集中,X为97*2,theta为1*2
inner=np.power((np.dot(X ,theta.T)-y),2)# power可以求次方得出一个矩阵;dot 矩阵相乘,此处得到一个值,而非一个矩阵
# a.dot(b)==np.dot(a,b) 矩阵a 乘 矩阵b ,一维数组时,ab位置无所谓
return np.sum(inner)/(2*len(X))
c=computeCost(Xnp,ynp,theta) # 没有使用梯度下降的误差值
print(c)
#梯度下降算法
def gD(X,y,theta,alpha=0.01,iters=1000):
temp=np.array(np.zeros(theta.shape))#初始化参数矩阵
cost=np.zeros(iters)#初始化一个数组,包含每次更新后的代价值
m=X.shape[0]#样本数目
for i in range(iters):
temp=theta-(alpha/m)*(X.dot(theta.T)-y).T.dot(X)
theta=temp
cost[i]=computeCost(X, y, theta)
return theta,cost#返回迭代一万次后的theta权重与迭代一万次的一万个损失值
final_theta,cost=gD(Xnp,ynp,theta)
final_cost=computeCost(Xnp,ynp,final_theta)#算出的cost跟第一万次的cost一样
population=np.linspace(data.Population.min(),data.Population.max(),97)#人口数的一维数组,从小到大排列
profit=final_theta[0,0]+ inal_theta[0,1]*population#得到预测出权重的数学模型
#绘制图像
fig, ax=plt.subplots(figsize=(8,6))
ax.plot()
ax.plot(population,profit,'r',label='Prediction')#最小损失直线
ax.scatter(data['Population'],data['Profit'],label='Training data')#散点
ax.legend(loc=4)#4表示标签在右下角
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Prediction Profit by. Population Size')
plt.show()
32.072733877455676
算法:基于梯度下降算法的线性回归是使用梯度下降算法进行收敛得到的最佳拟合参数,画出线性拟合的直线,数据集的点零散分布在平面内,使这些点尽可能分布在这条线上或周围。
链接:https://www.jianshu.com/p/c7e642877b0e
本文分享自 图像处理与模式识别研究所 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!