警告:本文为小白入门学习笔记

数据连接:

http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=DeepLearning&doc=exercises/ex2/ex2.html

数据集是(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简单应用的更多相关文章

  1. 机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables)

    机器学习(三)--------多变量线性回归(Linear Regression with Multiple Variables) 同样是预测房价问题  如果有多个特征值 那么这种情况下  假设h表示 ...

  2. 机器学习方法:回归(一):线性回归Linear regression

    欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld. 开一个机器学习方法科普系列:做基础回顾之用,学而时习之:也拿出来与大家分享.数学水平有限,只求易懂,学习与工 ...

  3. 斯坦福CS229机器学习课程笔记 Part1:线性回归 Linear Regression

    机器学习三要素 机器学习的三要素为:模型.策略.算法. 模型:就是所要学习的条件概率分布或决策函数.线性回归模型 策略:按照什么样的准则学习或选择最优的模型.最小化均方误差,即所谓的 least-sq ...

  4. ML 线性回归Linear Regression

    线性回归 Linear Regression MOOC机器学习课程学习笔记 1 单变量线性回归Linear Regression with One Variable 1.1 模型表达Model Rep ...

  5. TensorFlow 学习笔记(1)----线性回归(linear regression)的TensorFlow实现

    此系列将会每日持续更新,欢迎关注 线性回归(linear regression)的TensorFlow实现 #这里是基于python 3.7版本的TensorFlow TensorFlow是一个机器学 ...

  6. AI-IBM-cognitive class --Liner Regression

    Liner Regression import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy ...

  7. 通俗理解线性回归(Linear Regression)

    线性回归, 最简单的机器学习算法, 当你看完这篇文章, 你就会发现, 线性回归是多么的简单. 首先, 什么是线性回归. 简单的说, 就是在坐标系中有很多点, 线性回归的目的就是找到一条线使得这些点都在 ...

  8. Stanford机器学习---第二讲. 多变量线性回归 Linear Regression with multiple variable

    原文:http://blog.csdn.net/abcjennifer/article/details/7700772 本栏目(Machine learning)包括单参数的线性回归.多参数的线性回归 ...

  9. (三)用Normal Equation拟合Liner Regression模型

    继续考虑Liner Regression的问题,把它写成如下的矩阵形式,然后即可得到θ的Normal Equation. Normal Equation: θ=(XTX)-1XTy 当X可逆时,(XT ...

随机推荐

  1. ArrayList 初学小结!

    package good.com; import java.util.ArrayList;//导入 ArrayList 包 调用动态数组! public class ArrayListList { / ...

  2. springboot+jpa+mysql+redis+swagger整合步骤

    springboot+jpa+MySQL+swagger框架搭建好之上再整合redis: 在电脑上先安装redis: 一.在pom.xml中引入redis 二.在application.yml里配置r ...

  3. DeepLearning训练方法

    1.BN层训练技巧 缩小输入尺寸,这样可以提高batchsize的大小,在BN层适应了该数据集后,固定住BN层参数,放大输入尺寸继续训练 2.语义分割中解决网络输出尺寸与原尺寸的gap方法(如 1/8 ...

  4. Nginx 针对建立TCP连接优化

    L:124 sysctl -a | grep file-max //通过命令查看系统最大句柄数 [root@3 ~]# sysctl -a | grep file-max fs.file-max = ...

  5. 如何创建djiago项目和djiago连接数据库

    介绍 主要介绍在python中如何使用pycharm创建djiago项目以及如何将djiago项目和mysal数据库连接起来 创建djiago项目 1.使用pycharm创建djiao项目 点击pyc ...

  6. 一个服务器创建两个MySQL

    转载:http://www.2cto.com/database/201412/357863.html 将已安装的数据库文件夹复制到另一个目录下 打开复制目录下的my.ini文件修改 [client] ...

  7. gogs : 添加 ssh An error has occurred : addKey: fail to parse public key: exec: "ssh-keygen": executable file not found in %PATH% - exec: "ssh-keygen": executable file not found in %PATH%

    服务器上缺少配置   ssh-keygen.exe的 环境变量.git的环境变量 在path 环境变量加上.重启gogs服务

  8. Hdoj 1087.Super Jumping! Jumping! Jumping!

    Problem Description Nowadays, a kind of chess game called "Super Jumping! Jumping! Jumping!&quo ...

  9. JAVA 获取指定网址的IP地址 实例

    如今买票是一大难事,在高峰时段 打开12306网站,慢的像蜗牛,想到以前用修改hosts文件来登录Google(Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址 ...

  10. 【BZOJ5322】[JXOI2018]排序问题(模拟)

    [BZOJ5322][JXOI2018]排序问题(模拟) 题面 BZOJ 洛谷 题解 这题就显得很呆. 显然就是每次找到\([l,r]\)中出现次数最小的那个数并且放一个. 然后随便模拟一下就好了Qw ...