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

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. 清空KindEditor富文本编辑器里面的内容方法

    //清空KindEditorKindEditor.instances[0].html(""); 0表示第一个KindEditor编辑器对象 详情见链接:http://www.new ...

  2. window php redis扩展下载地址

    redis扩展下载 http://windows.php.net/downloads/pecl/snaps/redis/

  3. Swift开发小技巧--扫描二维码,二维码的描边与锁定,设置扫描范围,二维码的生成(高清,无码,你懂得!)

    二维码的扫描,二维码的锁定与描边,二维码的扫描范围,二维码的生成(高清,无码,你懂得!),识别相册中的二维码 扫描二维码用到的三个重要对象的关系,如图: 1.懒加载各种类 // MARK: - 懒加载 ...

  4. 【Tyvj 1060】【NOIP 2005】等价表达式

    设a为一个质数,模数为另一个质数,然后暴力算多项式的答案,如果答案相等就认为两个多项式相等. 这种hash有出错概率的题为什么还是要用hash呢?因为出错的概率实在太小了,a和模数的值取得好出题人根本 ...

  5. 512M内存编译php出错

    make时错误如下 virtual memory exhausted: Cannot allocate memory make: *** [ext/fileinfo/libmagic/apprenti ...

  6. eclipse-搭建maven的war项目集合spring注解方式

    工具:eclipse 4.4.2 版本号:20150219-0600 jdk:1.7 1.下图创建maven工程,然后next 下图选择工程保存位置(这里选择默认),next 下图选择webapp项目 ...

  7. python面试2

    Python语言特性 1 Python的函数参数传递 看两个例子:     1 2 3 4 5 a = 1 def fun(a):     a = 2 fun(a) print a  # 1 1 2 ...

  8. dede使用方法----实现英文版的搜索功能

    搜索功能在网站中是最常见的一个功能了.我们在用dede做双语网站的时候,默认的会有中文版的搜索功能.但是怎么添加一个英文版的搜索功能.各位看官,方法如下: 1.复制plus目录下的serach.php ...

  9. iOS的nil,Null,NSNull的使用

    今天做项目时,在数组里面取值时,发现里面有NSNull的对象,然后用数组里面对应的对象赋值时出现各种问题,总是报错.后面经过研究和查资料,总算解决了这一问题. nil用来给对象赋值(Objective ...

  10. 【BZOJ-3638&3272&3267&3502】k-Maximum Subsequence Sum 费用流构图 + 线段树手动增广

    3638: Cf172 k-Maximum Subsequence Sum Time Limit: 50 Sec  Memory Limit: 256 MBSubmit: 174  Solved: 9 ...