python梯度下降算法的实现

 更新时间:2020年02月24日 16:39:45   作者:epleone  
这篇文章主要为大家详细介绍了python实现梯度下降算法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了python实现梯度下降算法的具体代码,供大家参考,具体内容如下

简介

本文使用python实现了梯度下降算法,支持y = Wx+b的线性回归
目前支持批量梯度算法和随机梯度下降算法(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

# 使用随机数种子, 让每次的随机数生成相同,方便调试
# np.random.seed(111111111)


class GradientDescent(object):
 eps = 1.0e-8
 max_iter = 1000000 # 暂时不需要
 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):
 # 一维画图
 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()
 # 二维画图
 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')

 # 梯度下降法只能求解凸函数
 def _gradient_descent(self, bs, lr, epoch):
 x = self.x
 # shuffle数据集没有必要
 # 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时 等价单样本梯度下降
 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('拟合的结果为:', 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("要拟合的参数结果是: ")
 print(gd.FuncArgs)
 print("===================\n\n")
 # gd.EPS = 0.0
 gd.plotFunc()
 gd(10, 0.01)
 print("Finished!")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Pytorch实现常用乘法算子TensorRT的示例代码

    Pytorch实现常用乘法算子TensorRT的示例代码

    pytorch 用于训练,TensorRT用于推理是很多AI应用开发的标配。大家往往更加熟悉 pytorch 的算子,而不太熟悉TensorRT的算子。本文介绍了Pytorch中常用乘法的TensorRT实现,感兴趣的可以了解一下
    2022-06-06
  • python 2.7.14安装图文教程

    python 2.7.14安装图文教程

    这篇文章主要为大家详细介绍了python 2.7.14安装图文教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • Python可变参数用法实例分析

    Python可变参数用法实例分析

    这篇文章主要介绍了Python可变参数用法,结合实例形式分析了Python可变参数的具体定义、使用方法与相关注意事项,需要的朋友可以参考下
    2017-04-04
  • Python爬虫之urllib基础用法教程

    Python爬虫之urllib基础用法教程

    这篇文章主要为大家详细介绍了Python爬虫1.1 urllib基础用法教程,用于对Python爬虫技术进行系列文档讲解,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • python WindowsError的错误代码详解

    python WindowsError的错误代码详解

    这篇文章主要介绍了python WindowsError的错误代码详解,因为我们在书写pythone过程中,经常会遇到这样的错误,特分享一下需要的朋友可以参考下
    2017-07-07
  • opencv调用yolov3模型深度学习目标检测实例详解

    opencv调用yolov3模型深度学习目标检测实例详解

    这篇文章主要为大家介绍了opencv调用yolov3模型深度学习目标检测实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • 在Python 中将类对象序列化为JSON

    在Python 中将类对象序列化为JSON

    这篇文章主要介绍了在Python 中将类对象序列化为JSON,序列化是将对象转换为可以在以后保存和检索介质中的过程,下文具体的内容分享,需要的朋友可以参考一下
    2022-04-04
  • python scrapy框架中Request对象和Response对象的介绍

    python scrapy框架中Request对象和Response对象的介绍

    本文介绍了python基础之scrapy框架中Request对象和Response对象的介绍,Request对象主要是用来请求数据,爬取一页的数据重新发送一个请求的时候调用,Response对象一般是由scrapy给你自动构建的,因此开发者不需要关心如何创建Response对象,下面来一起来了解更多内容吧
    2022-02-02
  • Django实现简单分页功能的方法详解

    Django实现简单分页功能的方法详解

    这篇文章主要介绍了Django实现简单分页功能的方法,结合实例形式分析了django的第三方模块django-pure-pagination的安装、使用及实现分页的相关操作技巧,需要的朋友可以参考下
    2017-12-12
  • PyCharm活动模板设置步骤实现

    PyCharm活动模板设置步骤实现

    很多情况,我们在写代码都会存在经常要写一些简单且又重复的代码,Pycharm中的活动模板可以把这些使用频率很高的一些代码打包起来设置一个快捷键,本文就来介绍一下如何实现
    2023-12-12

最新评论