小言_互联网的博客

梯度下降法 - 多元线性回归

286人阅读  评论(0)

代码是我跟着网课学习自己敲得,数据源Delivery.csv我将会放在我的资源里,大家有兴趣可以试试

import numpy as np
from numpy import genfromtxt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#载入数据
data=genfromtxt(r"Delivery.csv",delimiter=",")
print(data)
x_data=data[:,0]
y_data=data[:,1]
plt.scatter(x_data,y_data)
plt.show()
print(x_data.shape)
#切分数据
#  :-1表示从第一列到最后一列,但是不包括最后一列
x_data=data[:,:-1]
y_data=data[:,-1]
print(x_data)
print(y_data)

#学习率learning rate 
lr=0.0001
#参数
theta0=0
theta1=0
theta2=0
#最大迭代次数
epochs=1000

#最小二乘法
def compute_error(theta0,theta1,theta2,x_data,y_data):
    totalError=0
    for i in range(0,len(x_data)):
        totalError+=(y_data[i]-(theta1*x_data[i,0]+theta1*x_data[i,1]+theta0))**2
    return totalError/float(len(x_data))/2.0

def gradient_descent_runner(x_data,y_data,theta0,theta1,theta2,lr,epochs):
    #计算总数据量
    m=float(len(x_data))
    #循环epochs次
    for i in range(epochs):
        theta0_grad=0
        theta1_grad=0
        theta2_grad=0
        #计算梯度的总和再求平均值
        for j in range(0,len(x_data)):
            theta0_grad += (1/m)*(theta1*x_data[j,0]+theta2*x_data[j,1]+theta0-y_data[j])
            theta1_grad += (1/m)*(theta1*x_data[j,0]+theta2*x_data[j,1]+theta0-y_data[j])*x_data[j,0]
            theta2_grad += (1/m)*(theta1*x_data[j,0]+theta2*x_data[j,1]+theta0-y_data[j])*x_data[j,1]
        #更新theta
        theta0=theta0-(lr*theta0_grad)
        theta1=theta1-(lr*theta1_grad)
        theta2=theta2-(lr*theta2_grad)
        #每迭代5次输出一次图像
    return theta0,theta1,theta2

print("Starting theta0={0},theta1={1},theta2={2},error={3}".format(theta0,theta1,theta2,compute_error(theta0,theta1,theta2,x_data,y_data)))
print("Running...")
theta0,theta1,theta2=gradient_descent_runner(x_data,y_data,theta0,theta1,theta2,lr,epochs)
print("After{0} iteration,theta0={1},theta1={2},theta2={3},error={4}".format(epochs,theta0,theta1,theta2,compute_error(theta0,theta1,theta2,x_data,y_data)))

#画图
ax=plt.figure().add_subplot(111,projection='3d')
ax.scatter(x_data[:,0],x_data[:,1],y_data,c='r',marker='o',s=100)
x0=x_data[:,0]
x1=x_data[:,1]
#生成网格矩阵
x0,x1=np.meshgrid(x0,x1)
z=theta0+x0*theta1+x1*theta2
#画3D图
ax.plot_surface(x0,x1,z)
#设置坐标轴
ax.set_xlabel('Miles')
ax.set_ylabel('Num of Delivery')
ax.set_zlabel('Time')
#显示图像
plt.show()

注:如有侵权,请联系删除!


转载:https://blog.csdn.net/qq_45313604/article/details/101374119
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场