欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现机器学习之多元线性回归

程序员文章站 2023-10-12 20:21:46
总体思路与一元线性回归思想一样,现在将数据以矩阵形式进行运算,更加方便。 下面是多元线性回归用python实现的代码: import numpy as...

总体思路与一元线性回归思想一样,现在将数据以矩阵形式进行运算,更加方便。

下面是多元线性回归用python实现的代码:

import numpy as np

def linearregression(data_x,data_y,learningrate,loopnum):
 w = np.zeros(shape=[1, data_x.shape[1]])
 # w的shape取决于特征个数,而x的行是样本个数,x的列是特征值个数
 # 所需要的w的形式为 行=特征个数,列=1 这样的矩阵。但也可以用1行,再进行转置:w.t
 # x.shape[0]取x的行数,x.shape[1]取x的列数
 b = 0

 #梯度下降
 for i in range(loopnum):
  w_derivative = np.zeros(shape=[1, data_x.shape[1]])
  b_derivative, cost = 0, 0

  wxplusb = np.dot(data_x, w.t) + b # w.t:w的转置
  w_derivative += np.dot((wxplusb - data_y).t, data_x) # np.dot:矩阵乘法
  b_derivative += np.dot(np.ones(shape=[1, data_x.shape[0]]), wxplusb - data_y)
  cost += (wxplusb - data_y)*(wxplusb - data_y)
  w_derivative = w_derivative / data_x.shape[0] # data_x.shape[0]:data_x矩阵的行数,即样本个数
  b_derivative = b_derivative / data_x.shape[0]


  w = w - learningrate*w_derivative
  b = b - learningrate*b_derivative

  cost = cost/(2*data_x.shape[0])
  if i % 100 == 0:
   print(cost)
 print(w)
 print(b)

if __name__== "__main__":
 x = np.random.normal(0, 10, 100)
 noise = np.random.normal(0, 0.05, 20)
 w = np.array([[3, 5, 8, 2, 1]]) #设5个特征值
 x = x.reshape(20, 5)  #reshape成20行5列
 noise = noise.reshape(20, 1)
 y = np.dot(x, w.t)+6 + noise
 linearregression(x, y, 0.003, 5000)

特别需要注意的是要弄清:矩阵的形状

在梯度下降的时候,计算两个偏导值,这里面的矩阵形状变化需要注意。

梯度下降数学式子:

python实现机器学习之多元线性回归 

以代码中为例,来分析一下梯度下降中的矩阵形状。
代码中设了5个特征。

python实现机器学习之多元线性回归

wxplusb = np.dot(data_x, w.t) + b

w是一个1*5矩阵,data_x是一个20*5矩阵
wxplusb矩阵形状=20*5矩阵乘上5*1(w的转置)的矩阵=20*1矩阵

w_derivative += np.dot((wxplusb - data_y).t, data_x)

w偏导矩阵形状=1*20矩阵乘上 20*5矩阵=1*5矩阵

b_derivative += np.dot(np.ones(shape=[1, data_x.shape[0]]), wxplusb - data_y)

b是一个数,用1*20的全1矩阵乘上20*1矩阵=一个数

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。