(线性回归)Liner Regression简单应用
警告:本文为小白入门学习笔记
数据连接:
数据集是(x(i),y(i))
x = load('ex2x.dat');
y = load('ex2y.dat');
plot(x, y, 'o');

假设函数(hypothesis function):

接下来用矩阵的形式表示x:
m = length(y); % store the number of training examples
x = [ones(m, 1), x]; % Add a column of ones to x

MATLAB实现:
function [jVal,gradient] = linerCost(theta)
x = load('ex2x.dat');
y = load('ex2y.dat');
m = length(y); % store the number of training examples
%x = [ones(m, 1), x]; % Add a column of ones to x
w = 0;
for i = 1:m
w = w + (theta(1) + theta(2) .* x(i) - y(i)).^2;
end
jVal = 1./2 .* m .* w;
gradient = zeros(2,1);
w = 0;
for i = 1:m
w = w + (theta(1) + theta(2) .* x(i) - y(i));
end
gradient(1) = w;
w = 0;
for i = 1:m
w = w + (theta(1) + theta(2) .* x(i) - y(i)).*x(i);
end
gradient(2) = w;
end
命令控制台:
>> options = optimset('GradObj','on','MaxIter',1000);
>> initialTheta = zeros(2,1);
>> [optTheta,functionVal,exitFlag] = fminunc(@costFunction,initialTheta ,options)
返回结果:
optTheta =
0.7502
0.0639
functionVal =
2.4677
exitFlag =
1
由于本案例只有一个feature,所以还可以在二维平面上查看结果,如果是高维度就无法看结果。

本实验中,theta的选择,和learning rate的选取都是由MATLAB自动实现的;
如果要自己手写
for i = 1:iter
theta = theta - X'*(X*theta-y)/m*alpha;
end
需要自己选取alpha,还有确定迭代的次数iter
如果使用矩阵直接计算会更加快而且准确(对于本题而言):

入门菜鸟,错误地方欢迎指教!
补充
局部加权线性回归
如果是以下数据集

左图可以看出,这是一种欠拟合的现象,怎么才能使拟合的更好呢?
使用高斯核 的 局部加权线性回归
高斯函数是


随着x与x′的距离的距离的增大,其高斯核函数值在单调递减。根据这个特点,可以对预测点在附近的每一点赋值,离预测点越近的点权重越大
用下面图说明

图中设黑色点是预测点,红色区域σ的值最小,随着σ的增大影响范围也在增大,而它的拟合曲线也在改变
所以可以通过改变σ的值来调整拟合的情况
整体来说,σ=1时把所有的点都包含,局部加权没有作用
当σ过小时会出现欠拟合现象
普通正规矩阵回归曲线
局部加权线性回归
岭回归
代码+注释
#coding=utf-8
from numpy import *
import matplotlib.pyplot as plt #加载数据
def loadDataSet(fileName):
numFeat = len(open(fileName).readline().split('\t')) - 1
dataMat = []; labelMat = []
fr = open(fileName)
for line in fr.readlines():
lineArr =[]
curLine = line.strip().split('\t')
for i in range(numFeat):
lineArr.append(float(curLine[i]))
dataMat.append(lineArr)
labelMat.append(float(curLine[-1]))
return dataMat,labelMat #使用正规矩阵来计算回归系数w(w[0]是系数b,w[1]是斜率k)
def standRegres(xArr,yArr):
xMat = mat(xArr); yMat = mat(yArr).T
xTx = xMat.T*xMat
#不可逆判断
if linalg.det(xTx) == 0.0:
print ("This matrix is singular, cannot do inverse")
return
ws = xTx.I * (xMat.T*yMat)
return ws #使用局部加权的线性回归
def lwlr(testPoint,xArr,yArr,k=1.0):
xMat = mat(xArr); yMat = mat(yArr).T
m = shape(xMat)[0]
weights = mat(eye((m)))
#为每一个样本点增加权重
for j in range(m):
diffMat = testPoint - xMat[j,:]
#使用高斯核函数来加权
weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2))
xTx = xMat.T * (weights * xMat)
if linalg.det(xTx) == 0.0:
print ("This matrix is singular, cannot do inverse")
return
ws = xTx.I * (xMat.T * (weights * yMat))
return testPoint * ws #循环测试每一个点testPoint
def lwlrTest(testArr,xArr,yArr,k=1.0):
m = shape(testArr)[0]
yHat = zeros(m)
for i in range(m):
yHat[i] = lwlr(testArr[i],xArr,yArr,k)
return yHat #岭回归
def rssError(yArr,yHatArr):
return ((yArr-yHatArr)**2).sum() def ridgeRegres(xMat,yMat,lam=0.2):
xTx = xMat.T*xMat
#增加一个m*m的单位矩阵乘lambda默认值是0.2
denom = xTx + eye(shape(xMat)[1])*lam
if linalg.det(denom) == 0.0:
print ("This matrix is singular, cannot do inverse")
return
ws = denom.I * (xMat.T*yMat)
return ws #不断的调增lambd的取值(增加),测试结果
def ridgeTest(xArr,yArr):
xMat = mat(xArr); yMat=mat(yArr).T
yMean = mean(yMat,0)
yMat = yMat - yMean #to eliminate X0 take mean off of Y
#regularize X's
xMeans = mean(xMat,0) #calc mean then subtract it off
xVar = var(xMat,0) #calc variance of Xi then divide by it
xMat = (xMat - xMeans)/xVar
numTestPts = 30
wMat = zeros((numTestPts,shape(xMat)[1]))
for i in range(numTestPts):
ws = ridgeRegres(xMat,yMat,exp(i-10))
wMat[i,:]=ws.T
return wMat #前向逐步向前线性回归
def regularize(xMat):#regularize by columns
inMat = xMat.copy()
inMeans = mean(inMat,0) #calc mean then subtract it off
inVar = var(inMat,0) #calc variance of Xi then divide by it
inMat = (inMat - inMeans)/inVar
return inMat def stageWise(xArr,yArr,eps=0.01,numIt=100):
xMat = mat(xArr); yMat=mat(yArr).T
yMean = mean(yMat,0)
yMat = yMat - yMean #can also regularize ys but will get smaller coef
xMat = regularize(xMat)
m,n=shape(xMat)
#returnMat = zeros((numIt,n)) #testing code remove
ws = zeros((n,1)); wsTest = ws.copy(); wsMax = ws.copy()
for i in range(numIt):
print ws.T
lowestError = inf;
for j in range(n):
for sign in [-1,1]:
wsTest = ws.copy()
wsTest[j] += eps*sign
yTest = xMat*wsTest
rssE = rssError(yMat.A,yTest.A)
if rssE < lowestError:
lowestError = rssE
wsMax = wsTest
ws = wsMax.copy()
returnMat[i,:]=ws.T
return returnMat def test1():
xArr,yArr = loadDataSet('ex0.txt')
ws = standRegres(xArr,yArr)
xMat = mat(xArr)
yMat = mat(yArr)
yHat = xMat * ws
#绘制数据集的散点图
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xMat[:,1].flatten().A[0],yMat.T[:,0].flatten().A[0])
#绘制回归曲线
xCopy = xMat.copy()
xCopy.sort(0)
yHat = xCopy * ws
ax.plot(xCopy[:,1],yHat)
plt.show() #-------------分割线-----以上是普通线性回归曲线------------------------ def test2():
xArr,yArr = loadDataSet('ex0.txt')
print (yArr[0])
#测试点xArr[0],在不同取值k下的ws
lwlr(xArr[0],xArr,yArr,1.0)
lwlr(xArr[0],xArr,yArr,0.001)
#调整k的取值来获得不同的拟合曲线
yHat = lwlrTest(xArr,xArr,yArr,0.003)
xMat = mat(xArr)
strInd = xMat[:,1].argsort(0)
xSort = xMat[strInd][:,0,:]
#绘制数据集的散点图
fig = plt.figure()
ax = fig.add_subplot(111)
#绘制回归曲线
ax.plot(xSort[:,1],yHat[strInd])
ax.scatter(xMat[:,1].flatten().A[0],mat(yArr).T.flatten().A[0],s=2,c='red')
plt.show() #-------------分割线-----以上是局部加权线性回归曲线------------------------
def test3():
abX,abY = loadDataSet('abalone.txt')
ridgeWeights = ridgeTest(abX,abY)
fig = plt.figure()
ax = fig.add_subplot(111)
#画出lambda的变化过程
ax.plot(ridgeWeights)
plt.show() #当lambda很小时,系数和普通回归一样,随着lambda增大,回归系数减小为零,可以在中间得到一个预测结果较好的lambda
(线性回归)Liner Regression简单应用的更多相关文章
- 机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables)
机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables) 同样是预测房价问题 如果有多个特征值 那么这种情况下 假设h表示 ...
- 机器学习方法:回归(一):线性回归Linear regression
欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld. 开一个机器学习方法科普系列:做基础回顾之用,学而时习之:也拿出来与大家分享.数学水平有限,只求易懂,学习与工 ...
- 斯坦福CS229机器学习课程笔记 Part1:线性回归 Linear Regression
机器学习三要素 机器学习的三要素为:模型.策略.算法. 模型:就是所要学习的条件概率分布或决策函数.线性回归模型 策略:按照什么样的准则学习或选择最优的模型.最小化均方误差,即所谓的 least-sq ...
- ML 线性回归Linear Regression
线性回归 Linear Regression MOOC机器学习课程学习笔记 1 单变量线性回归Linear Regression with One Variable 1.1 模型表达Model Rep ...
- TensorFlow 学习笔记(1)----线性回归(linear regression)的TensorFlow实现
此系列将会每日持续更新,欢迎关注 线性回归(linear regression)的TensorFlow实现 #这里是基于python 3.7版本的TensorFlow TensorFlow是一个机器学 ...
- AI-IBM-cognitive class --Liner Regression
Liner Regression import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy ...
- 通俗理解线性回归(Linear Regression)
线性回归, 最简单的机器学习算法, 当你看完这篇文章, 你就会发现, 线性回归是多么的简单. 首先, 什么是线性回归. 简单的说, 就是在坐标系中有很多点, 线性回归的目的就是找到一条线使得这些点都在 ...
- Stanford机器学习---第二讲. 多变量线性回归 Linear Regression with multiple variable
原文:http://blog.csdn.net/abcjennifer/article/details/7700772 本栏目(Machine learning)包括单参数的线性回归.多参数的线性回归 ...
- (三)用Normal Equation拟合Liner Regression模型
继续考虑Liner Regression的问题,把它写成如下的矩阵形式,然后即可得到θ的Normal Equation. Normal Equation: θ=(XTX)-1XTy 当X可逆时,(XT ...
随机推荐
- 创建简单的表单Demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- python之if使用方法举例
if使用方法举例: import random #随机生成1-100的整数 n = random.randint(1, 100) if n > 50: print(n, "> 5 ...
- C-Lodop设置页面一加载就打印
C-Lodop由于是服务不是np插件,调用打印语句(print或preview等)时机太早,在页面第一次加载完成后有几百毫秒时间等待WebSocket通讯服务准备完成,在没完成的时候会提示“C-Lod ...
- java JSP自定义标签
来至: http://blog.csdn.net/jiangwei0910410003/article/details/23915373 http://blog.csdn.net/jiangwei09 ...
- Installing Office Online Server for SharePoint 2016
Office Online Server is the next version of the Office Web Apps, which allows your users to view and ...
- Rest模式get,put,post,delete含义与区别
POST /uri 创建 DELETE /uri/xxx 删除 PUT /uri/xxx 更新或创建 GET /uri/xxx 查看 GET操作是安全的.所谓 ...
- 51nod 1636
1636 教育改革 我看过题解了还下了数据,表示很惭愧不想说什么,但还是说两句吧 sol: 因为差值很小只有100,所以对数组下标存的是(选择的数值和左端点的差值) f[i][j][k]即为第i天选了 ...
- Nginx CGI反向代理对照
陶辉104 CGI是什么? CGI全称是“通用网关接口”(Common Gateway Interface),HTTP服务器与你的或其它机器上的程序进行“交谈”的一种工具
- POJ2187-Beauty Contest-凸包
平面最远点对 由于点数为1e5,而整数点的情况下,凸包上点的个数为sqrt(M),M为范围. 这样求出凸包之后n^2枚举维护距离就可以了 否则就用旋转卡壳. 这里用了挑战上的做法,比较简洁. #inc ...
- 【XSY2612】Comb Avoiding Trees 生成函数 多项式求逆 矩阵快速幂
题目大意 本题的满二叉树定义为:不存在只有一个儿子的节点的二叉树. 定义一棵满二叉树\(A\)包含满二叉树\(B\)当且经当\(A\)可以通过下列三种操作变成\(B\): 把一个节点的两个儿子同时删掉 ...