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

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. lineNumber: 1; columnNumber: 1; 前言中不允许有内容

    周六项目还能运行,也没修改什么,周一来了启动项目,竟然报错了~~~ 这是遇到的错误提示: Cause: org.xml.sax.SAXParseException; lineNumber: 1; co ...

  2. Java网络编程——IP

    类:InetAdrress 该类主要用于表示互联网协议(IP对象)地址,且无构造方法 主要方法: public static InetAddress getLocalHost()-->返回本地主 ...

  3. Android Retrofit网络请求Service,@Path、@Query、@QueryMap、@FieldMap (转)

    GET请求 多个参数在URL问号之后,且个数不确定 http://api.stay4it.com/News?newsId=1&type=类型1- http://api.stay4it.com/ ...

  4. [转]js中confirm实现执行操作前弹出确认框的方法

    原文地址:http://www.jb51.net/article/56986.htm 本文实例讲述了js中confirm实现执行操作前弹出确认框的方法.分享给大家供大家参考.具体实现方法如下: 现在在 ...

  5. iOS开发小技巧--iOS8之后的cell自动计算高度

    cell高度自动计算步骤:

  6. mysql 表被锁处理方案

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

  7. Shell命令_for

    chmod 755 demo.sh ./demo.sh 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ...

  8. 树分治 点分治poj 2114

    存在2点间距离==k 输出AYE 否则输出NAY #include<stdio.h> #include<string.h> #include<algorithm> ...

  9. 状态压缩 CSU1129 送货到家

    多组数据 n n*n 邻接矩阵 dp[i][j] 以i结束的到j状态的最短的路径 过的有点莫名 #include<stdio.h> #include<algorithm> #i ...

  10. 将现有的sql脚本导入 Oracle 数据库,中文乱码问题

    将现有的sql 脚本导入 Oracle数据库 比如 在windows 系统下,可以写一个 bat 来实现直接导入 如:bat 中的内容如下,logs.log 将会记录执行日志 sqlplus user ...