Chinaunix首页 | 论坛 | 博客
  • 博客访问: 488043
  • 博文数量: 25
  • 博客积分: 111
  • 博客等级: 民兵
  • 技术积分: 1279
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-26 20:51
文章分类

全部博文(25)

文章存档

2014年(17)

2013年(8)

分类: Python/Ruby

2014-04-06 16:54:35


点击(此处)折叠或打开

  1. # -*- coding: utf-8 -*

  2. '''
  3.     线性回归与局部加权线性回归python代码
  4. '''

  5. from numpy import *

  6. def reression(testPoint,trainSet,targetSet):
  7.     xMat = mat(trainSet);yMat = mat(targetSet).T;
  8.     weight = lineRegression(xMat,yMat);
  9.     yHat = xMat*weight;
  10.     corrMat = corrcoef(yHat.T,yMat);
  11.     '''
  12.         |correlationCoefficient| > 0.8时称为高度相关,
  13.         当0.5< |correlationCoefficient|<0.8时称为显著相关,
  14.         当 0.3<|correlationCoefficient|<0.5时,成为低度相关,
  15.         当 |correlationCoefficient| < 0.3时,称为无相关
  16.     '''
  17.     if corrMat[0,1] < 0.5:
  18.         return LWLRegresssion(testPoint,xMat,yMat);
  19.     else:
  20.         return testPoint*weight;

  21. def lineRegression(xMat,yMat):
  22.     '''note:
  23.         weight = (X.T*X).I*(X.T*y)
  24.         mat.I: 求矩阵的逆
  25.         mat.T: 求矩阵的转置
  26.     '''
  27.     xTx = xMat.T * xMat;
  28.     if 0.0 == linalg.det(xTx):
  29.         return ridgeRegression(xMat,yMat);
  30.     else:
  31.         return xTx.I * (xMat.T * yMat);

  32. def LWLRegresssion (testPoint,xMat,yMat,k=1.0):
  33.     '''
  34.         k: 带宽
  35.         weight = (X.T*W*X).I *X.T*W*y
  36.         shape(mat): 返回矩阵的行与列,是一个元组结构
  37.         eye(m,m) or eye ((m)): 产生m个不同的m维单位向量
  38.     '''
  39.     r = shape(xMat)[0];
  40.     weight = mat(eye((r)));
  41.     for j in range(r):
  42.         diffMat = testPoint - xMat[j:,];
  43.         weight[j,j] = exp(diffMat.T*diffMat/(-2.0*k**2));
  44.     xTx = xMat.T*(weight*xMat);
  45.     if 0.0 == linalg.det(xTx):
  46.         return ridgeRegression(xMat,yMat,True);
  47.     else:
  48.         return testPoint*(xTx.I*(xMat*(weight*yMat)));

  49. def ridgeRegression(xMat,yMat,q = False,lam=0.2):
  50.     xTx = xMat.T;
  51.     if q:
  52.          w = mat(mat(eye((shape(xMat)[0]))))
  53.          xTx *= w*xMat;
  54.     else:
  55.         xTx *= xMat;
  56.     denom = xTx + lam*eye(shape(xMat)[1]);
  57.     if 0.0 == linalg.det (demon):
  58.         print("matrix is singular, cannot do inverse")
  59.         return;
  60.     else:
  61.         return demon.I*(xMat.T*yMat)
  62.     return
本文出自:http://blog.chinaunix.net/uid-28311809-id-4198028.html
阅读(7607) | 评论(0) | 转发(0) |
0

上一篇:python类型总结

下一篇:Nginx简单实例

给主人留下些什么吧!~~