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

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()

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

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

参考资料:

1.python编写类:http://blog.csdn.net/wklken/article/details/6313265

2.python中if __name__ == __main__的用法:http://www.cnblogs.com/herbert/archive/2011/09/27/2193482.html

3.matplotlab gallery:http://matplotlib.org/gallery.html

4.python批量梯度下降参考代码:http://www.91r.net/ask/17784587.html

线性回归和批量梯度下降法python的更多相关文章

  1. 【Python】机器学习之单变量线性回归 利用批量梯度下降找到合适的参数值

    [Python]机器学习之单变量线性回归 利用批量梯度下降找到合适的参数值 本题目来自吴恩达机器学习视频. 题目: 你是一个餐厅的老板,你想在其他城市开分店,所以你得到了一些数据(数据在本文最下方), ...

  2. 线性回归(最小二乘法、批量梯度下降法、随机梯度下降法、局部加权线性回归) C++

    We turn next to the task of finding a weight vector w which minimizes the chosen function E(w). Beca ...

  3. 1. 批量梯度下降法BGD 2. 随机梯度下降法SGD 3. 小批量梯度下降法MBGD

    排版也是醉了见原文:http://www.cnblogs.com/maybe2030/p/5089753.html 在应用机器学习算法时,我们通常采用梯度下降法来对采用的算法进行训练.其实,常用的梯度 ...

  4. 梯度下降法VS随机梯度下降法 (Python的实现)

    # -*- coding: cp936 -*- import numpy as np from scipy import stats import matplotlib.pyplot as plt # ...

  5. matlib实现梯度下降法

    样本文件下载:ex2Data.zip ex2x.dat文件中是一些2-8岁孩子的年龄. ex2y.dat文件中是这些孩子相对应的体重. 我们尝试用批量梯度下降法,随机梯度下降法和小批量梯度下降法来对这 ...

  6. 梯度下降法的python代码实现(多元线性回归)

    梯度下降法的python代码实现(多元线性回归最小化损失函数) 1.梯度下降法主要用来最小化损失函数,是一种比较常用的最优化方法,其具体包含了以下两种不同的方式:批量梯度下降法(沿着梯度变化最快的方向 ...

  7. 梯度下降法实现(Python语言描述)

    原文地址:传送门 import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use(['ggplo ...

  8. 梯度下降法原理与python实现

    梯度下降法(Gradient descent)是一个一阶最优化算法,通常也称为最速下降法. 要使用梯度下降法找到一个函数的局部极小值,必须向函数上当前点对应梯度(或者是近似梯度)的反方向的规定步长距离 ...

  9. 机器学习中梯度下降法原理及用其解决线性回归问题的C语言实现

    本文讲梯度下降(Gradient Descent)前先看看利用梯度下降法进行监督学习(例如分类.回归等)的一般步骤: 1, 定义损失函数(Loss Function) 2, 信息流forward pr ...

随机推荐

  1. JAVA多线程(一)

    进程与线程: 一个进程可以包含多个线程.多个线程可以并行,但是一个时间点只能有一个线程是运行状态. 线程的状态: 查看API可以,线程的状态分为五种: (JVM里面的状态:These states a ...

  2. 【日常笔记】java spring 注解读取文件

    获取后缀文件 <!-- 注解读取properties文件开始 @Value("#{configProperties['userPageSize']}")private Str ...

  3. mysql 表被锁处理方案

    1. 查询锁表信息 当前运行的所有事务 select * from information_schema.innodb_trx 当前出现的锁 select * from information_sch ...

  4. Ext-ajax请求数据

    Ext.Ajax.request({ url: webPath+'/news/newsEastmoneyList', method: 'POST', success: function (respon ...

  5. wamp服务下部署禅道或其它项目时访问缓慢的解决办法

    原因其实很简单: WAMP服务默认是不支持外网访问的,如果公司内外网在一起就会引起缓慢甚至超时的问题,直接修改WAPM的配置文件让它可以访问外网即可解决问题.   解决的方法/步骤   1.解决办法: ...

  6. C++ 异常机制分析

    C++异常机制概述 异常处理是C++的一项语言机制,用于在程序中处理异常事件.异常事件在C++中表示为异常对象.异常事件发生时,程序使用throw关键字抛出异常表达式,抛出点称为异常出现点,由操作系统 ...

  7. 7款应用最广泛的Linux桌面环境盘点

    转载:http://top.jobbole.com/34823/ 多样性应该是 Linux 最好的特性之一,用户可以不断尝试各种喜欢和新鲜玩法与花样,并从中找出最适合自己的应用.无论你是 Linux ...

  8. jdbc/ojdbc连oracle的三种方式(转)

    文章转自:http://blog.itpub.net/22664653/viewspace-1383092/ 前言  本文是一篇学习笔记,学习如何通过java jdbc /ojdbc 连接oracle ...

  9. yocto系统介绍

    The Yocto Project is an open source collaboration project that provides templates, tools and methods ...

  10. Vmware vsphere 网络架构

    VMware vSphere架构下服务器会虚拟出交换机来供ESX Host虚拟机来使用,虚拟交换机有两种,vSwitch虚拟交换机和vNetwork分布式虚拟交换机,每个ESX Host均有一个标准v ...