线性回归的正规方程解法与梯度下降解法的代码
2015-07-24 20:56
537 查看
理论参见:/article/9606365.html
梯度公式:
梯度公式:
__author__ = 'Chen' from numpy import * def linearRegresion(x,y,type=True,alpha=0.01): xrow = shape(x)[0] xcol = shape(x)[1] x = matrix(x) Y = matrix(y) # fill ones xone = ones((xrow,1)) X = hstack((xone,x)) X = matrix(X) # normal equiation if type == True: theta = (X.T*X).I*X.T*Y return theta else: # gradiant theta = matrix(random.random(xcol+1)) # iterations for iteration in range(1,10000): sums = 0 #gradient method for i in range(xrow): sums += (theta*X[i,:].T-Y[i,:])*X[i,:] theta -= alpha*sums/xrow return theta x= [[0,1,0],[0,0,1],[0,1,1],[1,1,1]] y= [[1],[2],[3],[4]] # calculate linearRegression by normal equation theta1 = linearRegresion(x,y) print theta1 #gradient descent theta2 = linearRegresion(x,y,False) print theta2
C:\Python27\python.exe C:/Users/Chen/PycharmProjects/mypython/courseraML/LinearRegression.py [[ 0.] [ 1.] [ 1.] [ 2.]] [[ 0.00709026 1.00390811 0.99480722 1.99480246]] Process finished with exit code 0
相关文章推荐
- C++第一节:类、对象、构造函数、setget
- struts2 模型分配问题和延迟加载问题
- 【C++系列】之 运算符重载
- JavaWeb实现登录注册与验证码。
- Asp.net web pages(Razor)的调试方法
- Java集合框架
- Java中的一些错误提示原因
- struts 拦截器入门&执行流程
- C语言课程设计-学生信息管理系统
- H.264 基础及 RTP 封包详解
- c++ 模板详解(一)
- H264编码 封装成MP4格式 视频流 RTP封包
- 读《代码整洁之道》前四章浅显印象 和 我所见的不整洁代码引以为戒
- C++每次读取一行字符串输入(学习笔记) (转)
- java常量使用
- 我的C++笔记(类与对象)
- 关于RTP时间戳及多媒体通信同步的问题/H264关于RTP协议的实现
- 关于RTP打包h264的时间戳要注意的问题
- uva1395 Kruskal算法求最小生成树
- 学习笔记---c#中的get与set学习