기울기 하강 파이썬 코드 구현 (다중 선형 회귀)

기울기 하강 파이썬 코드 구현 (다중 선형 회귀 최소화 손실 함수)

1 그래디언트 디센트 방법은 주로 구체적으로 다음과 같은 두 가지 방법을 포함하는 최적화 비교적 일반적인 방법은 상기 손실 함수를 최소화하는 데 사용되는 배치 구배 하강 방법 (상기 구배의 방향을 따라 빠른 검색 값)와 스토캐스틱 기울기 하강 방법 최소한으로 반복함으로써 수렴 (주로 확률 구배 하강)

(1) 배치 구배 하강

(2) 스토캐스틱 기울기 하강 방법 ( 고정 값으로 더 이상 담금질 기법의 원리를 이용하여, 연속적으로 감소 훈련 시간과 속도 ETA 증가되는 학습 없음)

 

 

(2) 상기 다수의 선형 회귀 수학 양자화 그라디언트 강하 산출 원리 :

 

 

3 파이썬 원리 기능 코드는 다음 두 가지 방법을 달성하기 위하여
(1) 배치 구배 하강 방법
# 다중 선형 회귀를 최소 손실 함수를 구하는 경사 하강 방법을 사용
NP AS 오기 NumPy와
AS 오기 matplotlib.pyplot의 PLT
NP한다. random.seed (666)
X = np.random.random (크기 = 100)
Y는 X = + 3.0 * + np.random.normal. (4) (크기 = 100)
X-x.reshape = (-1,1)
인쇄 (X- )
인쇄 (x.shape)
인쇄 (y.shape)
plt.scatter (X, Y)
plt.show ()
인쇄 (X-)
인쇄 (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<n:
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)

 

추천

출처www.cnblogs.com/Yanjy-OnlyOne/p/11311747.html