Python编程实现线性回归和批量梯度下降法代码实例


Posted in Python onJanuary 04, 2018

通过学习斯坦福公开课的线性规划和梯度下降,参考他人代码自己做了测试,写了个类以后有时间再去扩展,代码注释以后再加,作业好多:

import numpy as np
import matplotlib.pyplot as plt
import random

class dataMinning:
  datasets = []
  labelsets = []
  
  addressD = '' #Data folder
  addressL = '' #Label folder
  
  npDatasets = np.zeros(1)
  npLabelsets = np.zeros(1)
  
  cost = []
  numIterations = 0
  alpha = 0
  theta = np.ones(2)
  #pCols = 0
  #dRows = 0
  def __init__(self,addressD,addressL,theta,numIterations,alpha,datasets=None):
    if datasets is None:
      self.datasets = []
    else:
      self.datasets = datasets
    self.addressD = addressD
    self.addressL = addressL
    self.theta = theta
    self.numIterations = numIterations
    self.alpha = alpha
    
  def readFrom(self):
    fd = open(self.addressD,'r')
    for line in fd:
      tmp = line[:-1].split()
      self.datasets.append([int(i) for i in tmp])
    fd.close()
    self.npDatasets = np.array(self.datasets)

    fl = open(self.addressL,'r')
    for line in fl:
      tmp = line[:-1].split()
      self.labelsets.append([int(i) for i in tmp])
    fl.close()
    
    tm = []
    for item in self.labelsets:
      tm = tm + item
    self.npLabelsets = np.array(tm)

  def genData(self,numPoints,bias,variance):
    self.genx = np.zeros(shape = (numPoints,2))
    self.geny = np.zeros(shape = numPoints)

    for i in range(0,numPoints):
      self.genx[i][0] = 1
      self.genx[i][1] = i
      self.geny[i] = (i + bias) + random.uniform(0,1) * variance

  def gradientDescent(self):
    xTrans = self.genx.transpose() #
    i = 0
    while i < self.numIterations:
      hypothesis = np.dot(self.genx,self.theta)
      loss = hypothesis - self.geny
      #record the cost
      self.cost.append(np.sum(loss ** 2))
      #calculate the gradient
      gradient = np.dot(xTrans,loss)
      #updata, gradientDescent
      self.theta = self.theta - self.alpha * gradient
      i = i + 1
      
  
  def show(self):
    print 'yes'
    
if __name__ == "__main__":
  c = dataMinning('c:\\city.txt','c:\\st.txt',np.ones(2),100000,0.000005)
  c.genData(100,25,10)
  c.gradientDescent()
  cx = range(len(c.cost))
  plt.figure(1)
  plt.plot(cx,c.cost)
  plt.ylim(0,25000)
  plt.figure(2)
  plt.plot(c.genx[:,1],c.geny,'b.')
  x = np.arange(0,100,0.1)
  y = x * c.theta[1] + c.theta[0]
  plt.plot(x,y)
  plt.margins(0.2)
  plt.show()

Python编程实现线性回归和批量梯度下降法代码实例

图1. 迭代过程中的误差cost

Python编程实现线性回归和批量梯度下降法代码实例

图2. 数据散点图和解直线

总结

以上就是本文关于Python编程实现线性回归和批量梯度下降法代码实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

Python编程实现粒子群算法(PSO)详解

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
python编写的最短路径算法
Mar 25 Python
Python scikit-learn 做线性回归的示例代码
Nov 01 Python
基于Python函数的作用域规则和闭包(详解)
Nov 29 Python
python实现简易云音乐播放器
Jan 04 Python
python如何求解两数的最大公约数
Sep 27 Python
python+selenium实现自动抢票功能实例代码
Nov 23 Python
python浪漫表白源码
Apr 05 Python
Python TCP通信客户端服务端代码实例
Nov 21 Python
python GUI库图形界面开发之PyQt5复选框控件QCheckBox详细使用方法与实例
Feb 28 Python
pycharm新建Vue项目的方法步骤(图文)
Mar 04 Python
基于matplotlib xticks用法详解
Apr 16 Python
matplotlib阶梯图的实现(step())
Mar 02 Python
Python语言描述随机梯度下降法
Jan 04 #Python
微信小程序跳一跳游戏 python脚本跳一跳刷高分技巧
Jan 04 #Python
python使用xpath中遇到:到底是什么?
Jan 04 #Python
python使用itchat库实现微信机器人(好友聊天、群聊天)
Jan 04 #Python
python实现微信跳一跳辅助工具步骤详解
Jan 04 #Python
Python中实现最小二乘法思路及实现代码
Jan 04 #Python
Python找出最小的K个数实例代码
Jan 04 #Python
You might like
改造一台复古桌面收音机
2021/03/02 无线电
php使用ffmpeg获取视频信息并截图的实现方法
2016/05/03 PHP
PHP+Ajax实现的无刷新分页功能详解【附demo源码下载】
2017/07/03 PHP
javascript FormatNumber函数实现方法
2008/12/30 Javascript
JS获取父节点方法
2009/08/20 Javascript
使用JavaScript switch case 另类写法
2010/03/14 Javascript
关于JavaScript的with 语句的使用方法
2011/05/09 Javascript
jQuery实用基础超详细介绍
2013/04/11 Javascript
js中的scroll和offset 使用比较的实例与分析
2013/09/29 Javascript
浅析offsetLeft,Left,clientLeft之间的区别
2013/11/30 Javascript
JavaScript实现N皇后问题算法谜题解答
2014/12/29 Javascript
浅谈jquery点击label触发2次的问题
2016/06/12 Javascript
AngularJs基本特性解析(一)
2016/07/21 Javascript
iscroll.js滚动加载实例详解
2017/07/18 Javascript
vue form check 表单验证的实现代码
2018/12/09 Javascript
[06:45]2018DOTA2亚洲邀请赛 4.5 SOLO赛 Sccc vs Maybe
2018/04/06 DOTA
[01:01:52]完美世界DOTA2联赛PWL S2 GXR vs Magma 第二场 11.25
2020/11/26 DOTA
python抓取网页内容并进行语音播报的方法
2018/12/24 Python
Python爬虫学习之获取指定网页源码
2019/07/30 Python
TensorFLow 数学运算的示例代码
2020/04/21 Python
python PyAUtoGUI库实现自动化控制鼠标键盘
2020/09/09 Python
html5 桌面提醒:Notifycations应用介绍
2012/11/27 HTML / CSS
美国精品家居用品网站:US-Mattress
2016/08/24 全球购物
Melijoe英国官网:法国儿童时尚网站
2016/11/18 全球购物
佐卡伊官网:中国知名珠宝品牌
2017/02/05 全球购物
Desigual英国官网:在线购买原创服装
2018/03/09 全球购物
英国领先的餐饮折扣俱乐部:Gourmet Society
2020/07/26 全球购物
客户经理岗位职责
2013/12/08 职场文书
模范教师事迹材料
2014/02/10 职场文书
药品业务员岗位职责
2014/04/17 职场文书
小学生操行评语
2014/04/22 职场文书
师范生自荐信模板
2014/05/28 职场文书
村支部书记群众路线对照检查材料思想汇报
2014/10/08 职场文书
国际贸易实务实训报告
2014/11/05 职场文书
扬州个园导游词
2015/02/06 职场文书
换届选举主持词
2015/07/03 职场文书