欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python梯度下降算法的實(shí)現(xiàn)

 更新時(shí)間:2020年02月24日 16:39:45   作者:epleone  
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)梯度下降算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了python實(shí)現(xiàn)梯度下降算法的具體代碼,供大家參考,具體內(nèi)容如下

簡(jiǎn)介

本文使用python實(shí)現(xiàn)了梯度下降算法,支持y = Wx+b的線性回歸
目前支持批量梯度算法和隨機(jī)梯度下降算法(bs=1)
也支持輸入特征向量的x維度小于3的圖像可視化
代碼要求python版本>3.4

代碼

'''
梯度下降算法
Batch Gradient Descent
Stochastic Gradient Descent SGD
'''
__author__ = 'epleone'
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys

# 使用隨機(jī)數(shù)種子, 讓每次的隨機(jī)數(shù)生成相同,方便調(diào)試
# np.random.seed(111111111)


class GradientDescent(object):
 eps = 1.0e-8
 max_iter = 1000000 # 暫時(shí)不需要
 dim = 1
 func_args = [2.1, 2.7] # [w_0, .., w_dim, b]

 def __init__(self, func_arg=None, N=1000):
 self.data_num = N
 if func_arg is not None:
 self.FuncArgs = func_arg
 self._getData()

 def _getData(self):
 x = 20 * (np.random.rand(self.data_num, self.dim) - 0.5)
 b_1 = np.ones((self.data_num, 1), dtype=np.float)
 # x = np.concatenate((x, b_1), axis=1)
 self.x = np.concatenate((x, b_1), axis=1)

 def func(self, x):
 # noise太大的話, 梯度下降法失去作用
 noise = 0.01 * np.random.randn(self.data_num) + 0
 w = np.array(self.func_args)
 # y1 = w * self.x[0, ] # 直接相乘
 y = np.dot(self.x, w) # 矩陣乘法
 y += noise
 return y

 @property
 def FuncArgs(self):
 return self.func_args

 @FuncArgs.setter
 def FuncArgs(self, args):
 if not isinstance(args, list):
 raise Exception(
 'args is not list, it should be like [w_0, ..., w_dim, b]')
 if len(args) == 0:
 raise Exception('args is empty list!!')
 if len(args) == 1:
 args.append(0.0)
 self.func_args = args
 self.dim = len(args) - 1
 self._getData()

 @property
 def EPS(self):
 return self.eps

 @EPS.setter
 def EPS(self, value):
 if not isinstance(value, float) and not isinstance(value, int):
 raise Exception("The type of eps should be an float number")
 self.eps = value

 def plotFunc(self):
 # 一維畫(huà)圖
 if self.dim == 1:
 # x = np.sort(self.x, axis=0)
 x = self.x
 y = self.func(x)
 fig, ax = plt.subplots()
 ax.plot(x, y, 'o')
 ax.set(xlabel='x ', ylabel='y', title='Loss Curve')
 ax.grid()
 plt.show()
 # 二維畫(huà)圖
 if self.dim == 2:
 # x = np.sort(self.x, axis=0)
 x = self.x
 y = self.func(x)
 xs = x[:, 0]
 ys = x[:, 1]
 zs = y
 fig = plt.figure()
 ax = fig.add_subplot(111, projection='3d')
 ax.scatter(xs, ys, zs, c='r', marker='o')

 ax.set_xlabel('X Label')
 ax.set_ylabel('Y Label')
 ax.set_zlabel('Z Label')
 plt.show()
 else:
 # plt.axis('off')
 plt.text(
 0.5,
 0.5,
 "The dimension(x.dim > 2) \n is too high to draw",
 size=17,
 rotation=0.,
 ha="center",
 va="center",
 bbox=dict(
 boxstyle="round",
 ec=(1., 0.5, 0.5),
 fc=(1., 0.8, 0.8), ))
 plt.draw()
 plt.show()
 # print('The dimension(x.dim > 2) is too high to draw')

 # 梯度下降法只能求解凸函數(shù)
 def _gradient_descent(self, bs, lr, epoch):
 x = self.x
 # shuffle數(shù)據(jù)集沒(méi)有必要
 # np.random.shuffle(x)
 y = self.func(x)
 w = np.ones((self.dim + 1, 1), dtype=float)
 for e in range(epoch):
 print('epoch:' + str(e), end=',')
 # 批量梯度下降,bs為1時(shí) 等價(jià)單樣本梯度下降
 for i in range(0, self.data_num, bs):
 y_ = np.dot(x[i:i + bs], w)
 loss = y_ - y[i:i + bs].reshape(-1, 1)
 d = loss * x[i:i + bs]
 d = d.sum(axis=0) / bs
 d = lr * d
 d.shape = (-1, 1)
 w = w - d

 y_ = np.dot(self.x, w)
 loss_ = abs((y_ - y).sum())
 print('\tLoss = ' + str(loss_))
 print('擬合的結(jié)果為:', end=',')
 print(sum(w.tolist(), []))
 print()
 if loss_ < self.eps:
 print('The Gradient Descent algorithm has converged!!\n')
 break
 pass

 def __call__(self, bs=1, lr=0.1, epoch=10):
 if sys.version_info < (3, 4):
 raise RuntimeError('At least Python 3.4 is required')
 if not isinstance(bs, int) or not isinstance(epoch, int):
 raise Exception(
 "The type of BatchSize/Epoch should be an integer number")
 self._gradient_descent(bs, lr, epoch)
 pass

 pass


if __name__ == "__main__":
 if sys.version_info < (3, 4):
 raise RuntimeError('At least Python 3.4 is required')

 gd = GradientDescent([1.2, 1.4, 2.1, 4.5, 2.1])
 # gd = GradientDescent([1.2, 1.4, 2.1])
 print("要擬合的參數(shù)結(jié)果是: ")
 print(gd.FuncArgs)
 print("===================\n\n")
 # gd.EPS = 0.0
 gd.plotFunc()
 gd(10, 0.01)
 print("Finished!")

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python利用pandas和matplotlib實(shí)現(xiàn)繪制雙柱狀圖

    Python利用pandas和matplotlib實(shí)現(xiàn)繪制雙柱狀圖

    在數(shù)據(jù)分析和可視化中,常用的一種圖形類型是柱狀圖,柱狀圖能夠清晰地展示不同分類變量的數(shù)值,并支持多組數(shù)據(jù)進(jìn)行對(duì)比,本篇文章將介紹python如何使用pandas和matplotlib繪制雙柱狀圖,需要的可以參考下
    2023-11-11
  • 基于Python實(shí)現(xiàn)的影視數(shù)據(jù)智能分析系統(tǒng)

    基于Python實(shí)現(xiàn)的影視數(shù)據(jù)智能分析系統(tǒng)

    數(shù)據(jù)分析與可視化是當(dāng)今數(shù)據(jù)分析的發(fā)展方向,大數(shù)據(jù)時(shí)代,數(shù)據(jù)資源具有海量特征,數(shù)據(jù)分析和可視化主要通過(guò)Python數(shù)據(jù)分析來(lái)實(shí)現(xiàn),本文給大家介紹了如何基于Python實(shí)現(xiàn)的影視數(shù)據(jù)智能分析系統(tǒng),文中給出了部分詳細(xì)代碼,感興趣的朋友跟著小編一起來(lái)看看吧
    2024-01-01
  • 基于Django與ajax之間的json傳輸方法

    基于Django與ajax之間的json傳輸方法

    今天小編就為大家分享一篇基于Django與ajax之間的json傳輸方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • Python動(dòng)態(tài)強(qiáng)類型解釋型語(yǔ)言原理解析

    Python動(dòng)態(tài)強(qiáng)類型解釋型語(yǔ)言原理解析

    這篇文章主要介紹了Python動(dòng)態(tài)強(qiáng)類型解釋型語(yǔ)言原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • 如何用Pytorch搭建一個(gè)房?jī)r(jià)預(yù)測(cè)模型

    如何用Pytorch搭建一個(gè)房?jī)r(jià)預(yù)測(cè)模型

    這篇文章主要介紹了用Pytorch搭建一個(gè)房?jī)r(jià)預(yù)測(cè)模型,在這里我將主要討論P(yáng)yTorch建模的相關(guān)方面,作為一點(diǎn)額外的內(nèi)容,我還將演示PyTorch中開(kāi)發(fā)的模型的神經(jīng)元重要性,需要的朋友可以參考下
    2023-03-03
  • Hadoop中的Python框架的使用指南

    Hadoop中的Python框架的使用指南

    這篇文章主要介紹了Hadoop中的Python框架的使用指南,Hadoop一般使用復(fù)雜的Java操作,但通過(guò)該框架使得Python腳本操作Hadoop成為了可能,需要的朋友可以參考下
    2015-04-04
  • Python學(xué)習(xí)之a(chǎn)syncore模塊用法實(shí)例教程

    Python學(xué)習(xí)之a(chǎn)syncore模塊用法實(shí)例教程

    這篇文章主要介紹了Python學(xué)習(xí)之a(chǎn)syncore模塊用法,主要講述了asyncore模塊的組成、原理及相關(guān)函數(shù)的用法,對(duì)于使用Python進(jìn)行網(wǎng)絡(luò)編程來(lái)說(shuō)非常實(shí)用,需要的朋友可以參考下
    2014-09-09
  • python開(kāi)發(fā)中range()函數(shù)用法實(shí)例分析

    python開(kāi)發(fā)中range()函數(shù)用法實(shí)例分析

    這篇文章主要介紹了python開(kāi)發(fā)中range()函數(shù)用法,以實(shí)例形式較為詳細(xì)的分析了Python中range()函數(shù)遍歷列表的相關(guān)技巧,需要的朋友可以參考下
    2015-11-11
  • python正則表達(dá)式re模塊詳解

    python正則表達(dá)式re模塊詳解

    re 模塊包含對(duì)正則表達(dá)式的支持,因?yàn)樵?jīng)系統(tǒng)學(xué)習(xí)過(guò)正則表達(dá)式,所以基礎(chǔ)內(nèi)容略過(guò),直接看 python 對(duì)于正則表達(dá)式的支持。
    2014-06-06
  • Python實(shí)現(xiàn)基于多線程、多用戶的FTP服務(wù)器與客戶端功能完整實(shí)例

    Python實(shí)現(xiàn)基于多線程、多用戶的FTP服務(wù)器與客戶端功能完整實(shí)例

    這篇文章主要介紹了Python實(shí)現(xiàn)基于多線程、多用戶的FTP服務(wù)器與客戶端功能,結(jié)合完整實(shí)例形式分析了Python多線程、多用戶FTP服務(wù)器端與客戶端相關(guān)實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下
    2017-08-08

最新評(píng)論