python梯度下降法实现线性回归_梯度下降法的python代码实现(多元线性回归)
梯度下降法的python代碼實現(多元線性回歸最小化損失函數)
1、梯度下降法主要用來最小化損失函數,是一種比較常用的最優化方法,其具體包含了以下兩種不同的方式:批量梯度下降法(沿著梯度變化最快的方向進行搜索最小值)和隨機梯度下降法(主要隨機梯度下降,通過迭代運算,收斂到最小值)
(1)批量梯度下降法
(2)隨機梯度下降法(學習率eta隨著訓練次數的增大而不斷減小,采用了模擬退火的原理,不再是定值)
2、多元線性回歸中的梯度下降法的向量化的數學計算原理:
3、兩種方法的python代碼原理函數實現如下:
(1)批量梯度下降法:
#多元線性回歸中使用梯度下降法來求得損失函數的最小值
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(666)
x=np.random.random(size=100)
y=x*3.0+4+np.random.normal(size=100)
X=x.reshape(-1,1)
print(X)
print(x.shape)
print(y.shape)
plt.scatter(x,y)
plt.show()
print(X)
print(len(X))
#1使用梯度下降法訓練
def J1(theta,x_b,y):
return np.sum((y-x_b.dot(theta))**2)/len(x_b)
def DJ2(theta,x_b,y):
res=np.empty(len(theta))
res[0]=np.sum(x_b.dot(theta)-y)
for i in range(1,len(theta)):
res[i]=np.sum((x_b.dot(theta)-y).dot(x_b[:,i]))
return res*2/len(x_b)
def DJ1(theta, x_b, y):
return x_b.T.dot(x_b.dot(theta)-y)*2/len(y)
def gradient_descent1(x_b,y,eta,theta_initial,erro=1e-8, n=1e4):
theta=theta_initial
i=0
while i
gradient = DJ1(theta,x_b,y)
last_theta = theta
theta = theta - gradient * eta
if (abs(J1(theta,x_b,y) - J1(last_theta,x_b,y))) < erro:
break
i+=1
return theta
x_b=np.hstack([np.ones((len(X),1)),X])
print(x_b)
theta0=np.zeros(x_b.shape[1])
eta=0.1
theta1=gradient_descent1(x_b,y,eta,theta0)
print(theta1)
from sklearn.linear_model import LinearRegression
l=LinearRegression()
l.fit(X,y)
print(l.coef_)
print(l.intercept_)
#2隨機梯度下降法的函數原理代碼(多元線性回歸為例):
#1-1寫出損失函數的表達式子
def J_SGD(theta, x_b, y):
return np.sum((y - x_b.dot(theta)) ** 2) / len(x_b)
#1-2寫出梯度胡表達式
def DJ_SGD(theta, x_b_i, y_i):
return x_b_i.T.dot(x_b_i.dot(theta)-y_i)*2
#1-3寫出SGD隨機梯度的函數形式
def SGD(x_b, y, theta_initial, n):
t0=5
t1=50
def learning_rate(t):
return t0/(t+t1) #計算學習率eta的表達式,需要隨著次數的增大而不斷的減小
theta = theta_initial #定義初始化的點(列陣)
for i1 in range(n): #采用不斷增加次數迭代計算的方式來進行相關的計算
rand_i=np.random.randint(len(x_b)) #生成隨機的索引值,計算隨機梯度
gradient = DJ_SGD(theta, x_b[rand_i], y[rand_i])
theta = theta - gradient *learning_rate(i1)
return theta
np.random.seed(666)
x=np.random.random(size=100)
y=x*3.0+4+np.random.normal(size=100)
X=x.reshape(-1,1)
print(X)
print(x.shape)
print(y.shape)
plt.scatter(x,y)
plt.show()
print(X)
print(len(X))
#1-4初始化數據x,y以及定義超參數theta0,迭代次數n
x_b=np.hstack([np.ones((len(X),1)),X])
print(x_b)
theta0=np.zeros(x_b.shape[1])
theta1=SGD(x_b,y,theta0,100000)
print(theta1)
原文:https://www.cnblogs.com/Yanjy-OnlyOne/p/11311747.html
總結
以上是生活随笔為你收集整理的python梯度下降法实现线性回归_梯度下降法的python代码实现(多元线性回归)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 内存条装多大?三个方面告诉你答案
- 下一篇: flask执行python脚本_如何在F