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

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. Python 一些总结和比较

    数据类型

  2. vs2012 发布网站,

    如图这样选择就没有可以得到一个不包括 *.aspx.cs 的网站了.

  3. 收藏Javascript中常用的55个经典技巧

    1. oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键 <table border oncontextmenu ...

  4. PS转手绘

    2014-08-03  一.人物皮肤处理 复制两层图层,对背景图层隐藏,最后一层 高斯模糊 ,按住ALT创建图层蒙版, 使用画笔工具涂抹人物皮肤,眼睛不涂,把阴影和高光处抹均匀,最后应用图层蒙版,向下 ...

  5. Linux_cheat命令安装和使用

      1.安装python yum -y install python   2.安装epel源.安装pip yum install epel-release -y  yum install python ...

  6. 单例模式(Singleton Pattern)

    意图 保证一个类仅有一个实例,并提供一个该实例的全局访问点 可将一个实例扩展到n个实例.限定某类最多只能创建n个实例. 双重锁定实现单例模式 C# public sealed class Single ...

  7. JavaScript的由来, 浏览器的20年

    在很久以前那时候还没有Yahoo,Google....人们还在用28.8kbit/s的"猫"上网, 用户注册或者登录的时候所有的验证都是在服务器验证的, 如果用户注册的时候用户名或 ...

  8. js-处理回车事件

    /**回车 */ function enterkey() { //兼容IE或其它其它浏览器 var event = arguments[0] || window.event; //兼容IE或其它浏览器 ...

  9. 14 接口-interface的定义与实现

    接口的基本语法一: 1.使用interface 定义 2.接口当中的方法都是抽象方法 3.接口当中的方法都是public权限 接口的定义: interface USB { public void re ...

  10. wow.js使用方法

    近日,在做项目中,需要做到滚动条滑到某个位置时,才能显示动画,网上查询到有个wow.js可以达到要求,现在把使用方法做如下总结: wow.js演示地址 wow.js的github地址 使用方法真是超简 ...