1. 程式人生 > 程式設計 >python實現梯度下降法

python實現梯度下降法

本文例項為大家分享了python實現梯度下降法的具體程式碼,供大家參考,具體內容如下

使用工具:Python(x,y) 2.6.6
執行環境:Windows10

問題:求解y=2*x1+x2+3,即使用梯度下降法求解y=a*x1+b*x2+c中引數a,b,c的最優值(監督學習)

訓練資料:

x_train=[1,2],[2,1],3],[3,5],[1,[4,[7,[11,[8,7]

y_train=[7,8,10,14,13,20,16,28,26]

測試資料:

x_test = [1,4],[5,1]

# -*- coding: utf-8 -*-
"""
Created on Wed Nov 16 09:37:03 2016
@author: Jason
"""
 
import numpy as np
import matplotlib.pyplot as plt
 
# y=2 * (x1) + (x2) + 3 
 
rate = 0.001
x_train = np.array([[1,7] ])
y_train = np.array([7,26])
x_test = np.array([[1,1]])
 
a = np.random.normal()
b = np.random.normal()
c = np.random.normal()
 
def h(x):
 return a*x[0]+b*x[1]+c
 
for i in range(100):
 sum_a=0
 sum_b=0
 sum_c=0
 
 for x,y in zip(x_train,y_train):  
  for xi in x:
   sum_a = sum_a+ rate*(y-h(x))*xi
   sum_b = sum_b+ rate*(y-h(x))*xi
   #sum_c = sum_c + rate*(y-h(x)) *1   
   
   a = a + sum_a
   b = b + sum_b
   c = c + sum_c
   plt.plot([h(xi) for xi in x_test])
 
 
print(a)
print(b)
print(c)
 
result=[h(xi) for xi in x_train]
print(result)
 
result=[h(xi) for xi in x_test]
print(result)
 
plt.show()

執行結果:

python實現梯度下降法

結論:線段是在逐漸逼近的,訓練資料越多,迭代次數越多就越逼近真實值。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。