鱼C论坛

 找回密码
 立即注册
查看: 1636|回复: 0

[技术交流] python实现线性回归的两种算法

[复制链接]
发表于 2017-6-3 21:14:40 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import numpy as np

  2. #y=3*x0 + 2 * (x1) + (x2)
  3. # x0 = 1
  4. x_train = np.array([    [1, 2],    [2, 1],    [2, 3],    [3, 5],    [1, 3],    [4, 2],    [7, 3],    [4, 5],    [11, 3],    [8, 7]    ])
  5. y_train = np.array([[7, 8, 10, 14, 8, 13, 20, 16, 28, 26]])
  6. x_test  = np.array([    [1, 4],    [2, 2],    [2, 5],    [5, 3],    [1, 5],    [4, 1]    ])


  7. ###最小二乘法  系数 = (X.T * X)^-1 * X.T * Y
  8. def function1(x_train,y_train):
  9.     m,n = x_train.shape
  10.     x = np.ones((m,1))
  11.     x_train = np.hstack((x,x_train)) ###增加x0 = 1这个特征
  12.     x_train_T = x_train.T
  13.     x_x_t = x_train_T.dot(x_train)  
  14.     x_x_t_ = np.linalg.inv(x_x_t)
  15.     x_x_t_t = x_x_t_.dot(x_train_T)
  16.     y_train = y_train.T
  17.     theat = x_x_t_t.dot(y_train)
  18.     return theat

  19. ###梯度下降法
  20. # rate表示学习速率,不可太大,也不可太小
  21. # theat表示初始化的系数,颗随便给
  22. # num表示有几组数据
  23. # minnum表示当原来的theat与求出的theat相差多少时,认为收敛
  24. def function2(x_train,y_train,rate,theat,num,minnum=0.000001):
  25.     m,n = x_train.shape
  26.     x = np.ones((m,1))
  27.     x_train = np.hstack((x,x_train)) ###增加x0 = 1这个特征
  28.     x_train_T = x_train.T
  29.     y_train = y_train.T
  30.     theat = theat.reshape(n+1,1)
  31.     while True:
  32.         y = x_train.dot(theat)
  33.         y_ = (y - y_train).T
  34.         de = y_.dot(x_train) * rate / num
  35.         theat = theat - de.T
  36.         f = abs(de) < minnum
  37.         if f.all():
  38.             break
  39.     return theat
  40. theat = np.array([0,0,0])


  41. print  function1(x_train,y_train)
  42. print  function2(x_train,y_train,rate=0.01,theat=theat,num=10)
复制代码


Python 2.7
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 05:49

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表