机器学习之线性回归算法Linear Regression(python代码实现)

        线性回归(Linear Regression)是一种非常简单、用处非常广泛、含义也非常容易理解的一类经典的算法,非常合适作为机器学习的入门算法。

        线性回归就是拟合出一个线性组合关系的函数。要找一条直线,并且让这条直线尽可能地拟合所有数据点。即:试图找到一条直线,使所有样本到直线上的欧式距离之和最小。

一元线性回归(Linear Regression

拟合出一个线性组合关系的函数:y = wx+b 。

 拟合图像:

多元线性回归

        多元线性回归比一元线性回归复杂,其组成的不是直线,而是一个多维空间中的超平面,数据点散落在超平面的两侧。

求解方法:

1、最小二乘法(least square method):均方误差最小化。
        最小二乘估计。
        对w和b分别求偏导。

2、梯度下降(gradient descent):近似逼近,一种迭代方法。
        对向量求偏导。

最小二乘法与梯度下降

相同点:
1)本质和目标相同:

        二者都是经典的学习算法,在给定已知数据的前提下利用求导算出一个模型(函数),使得损失函数值最小,后对给定的新数据进行估算预测。
不同点:
1)损失函数不同:

        梯度下降可以选取其它损失函数;而最小二乘法一定是平方损失函数。
2)实现方法不同:

        最小二乘法是直接求导找出全局最小;而梯度下降是一种迭代法。
3)效果不同:

        最小二乘法一定是全局最小,但计算繁琐,且复杂情况下未必有解;梯度下降迭代计算简单,但找到的一般是局部最小,只有在目标函数是凸函数时才是全局最小,到最小点附近收敛速度会变慢,且对初始点的选择极为敏感。

python代码实现

一元线性回归(最小二乘法、梯度下降法、sklearn库实现

最小二乘法


    
    
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # ---------------1. 准备数据----------
  4. data = np.array([[ 32, 31],[ 53, 68],[ 61, 62],[ 47, 71],[ 59, 87],[ 55, 78],[ 52, 79],[ 39, 59],[ 48, 75],[ 52, 71],
  5. [ 45, 55],[ 54, 82],[ 44, 62],[ 58, 75],[ 56, 81],[ 48, 60],[ 44, 82],[ 60, 97],[ 45, 48],[ 38, 56],
  6. [ 66, 83],[ 65, 118],[ 47, 57],[ 41, 51],[ 51, 75],[ 59, 74],[ 57, 95],[ 63, 95],[ 46, 79],[ 50, 83]])
  7. # 提取data中的两列数据,分别作为x,y
  8. x = data[:, 0]
  9. y = data[:, 1]
  10. # 用plt画出散点图
  11. #plt.scatter(x, y)
  12. #plt.show()
  13. # -----------2. 定义损失函数------------------
  14. # 损失函数是系数的函数,另外还要传入数据的x,y
  15. def compute_cost( w, b, points):
  16. total_cost = 0
  17. M = len(points)
  18. # 逐点计算平方损失误差,然后求平均数
  19. for i in range(M):
  20. x = points[i, 0]
  21. y = points[i, 1]
  22. total_cost += (y - w * x - b) ** 2
  23. return total_cost / M
  24. # ------------3.定义算法拟合函数-----------------
  25. # 先定义一个求均值的函数
  26. def average( data):
  27. sum = 0
  28. num = len(data)
  29. for i in range(num):
  30. sum += data[i]
  31. return sum / num
  32. # 定义核心拟合函数
  33. def fit( points):
  34. M = len(points)
  35. x_bar = average(points[:, 0])
  36. sum_yx = 0
  37. sum_x2 = 0
  38. sum_delta = 0
  39. for i in range(M):
  40. x = points[i, 0]
  41. y = points[i, 1]
  42. sum_yx += y * (x - x_bar)
  43. sum_x2 += x ** 2
  44. # 根据公式计算w
  45. w = sum_yx / (sum_x2 - M * (x_bar ** 2))
  46. for i in range(M):
  47. x = points[i, 0]
  48. y = points[i, 1]
  49. sum_delta += (y - w * x)
  50. b = sum_delta / M
  51. return w, b
  52. # ------------4. 测试------------------
  53. w, b = fit(data)
  54. print( "w is: ", w)
  55. print( "b is: ", b)
  56. cost = compute_cost(w, b, data)
  57. print( "cost is: ", cost)
  58. # ---------5. 画出拟合曲线------------
  59. plt.scatter(x, y)
  60. # 针对每一个x,计算出预测的y值
  61. pred_y = w * x + b
  62. plt.plot(x, pred_y, c= 'r')
  63. plt.show()

梯度下降法


    
    
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 准备数据
  4. data = np.array([[ 32, 31], [ 53, 68], [ 61, 62], [ 47, 71], [ 59, 87], [ 55, 78], [ 52, 79], [ 39, 59], [ 48, 75], [ 52, 71],
  5. [ 45, 55], [ 54, 82], [ 44, 62], [ 58, 75], [ 56, 81], [ 48, 60], [ 44, 82], [ 60, 97], [ 45, 48], [ 38, 56],
  6. [ 66, 83], [ 65, 118], [ 47, 57], [ 41, 51], [ 51, 75], [ 59, 74], [ 57, 95], [ 63, 95], [ 46, 79],
  7. [ 50, 83]])
  8. x = data[:, 0]
  9. y = data[:, 1]
  10. # --------------2. 定义损失函数--------------
  11. def compute_cost( w, b, data):
  12. total_cost = 0
  13. M = len(data)
  14. # 逐点计算平方损失误差,然后求平均数
  15. for i in range(M):
  16. x = data[i, 0]
  17. y = data[i, 1]
  18. total_cost += (y - w * x - b) ** 2
  19. return total_cost / M
  20. # --------------3. 定义模型的超参数------------
  21. alpha = 0.0001
  22. initial_w = 0
  23. initial_b = 0
  24. num_iter = 10
  25. # --------------4. 定义核心梯度下降算法函数-----
  26. def grad_desc( data, initial_w, initial_b, alpha, num_iter):
  27. w = initial_w
  28. b = initial_b
  29. # 定义一个list保存所有的损失函数值,用来显示下降的过程
  30. cost_list = []
  31. for i in range(num_iter):
  32. cost_list.append(compute_cost(w, b, data))
  33. w, b = step_grad_desc(w, b, alpha, data)
  34. return [w, b, cost_list]
  35. def step_grad_desc( current_w, current_b, alpha, data):
  36. sum_grad_w = 0
  37. sum_grad_b = 0
  38. M = len(data)
  39. # 对每个点,代入公式求和
  40. for i in range(M):
  41. x = data[i, 0]
  42. y = data[i, 1]
  43. sum_grad_w += (current_w * x + current_b - y) * x
  44. sum_grad_b += current_w * x + current_b - y
  45. # 用公式求当前梯度
  46. grad_w = 2 / M * sum_grad_w
  47. grad_b = 2 / M * sum_grad_b
  48. # 梯度下降,更新当前的w和b
  49. updated_w = current_w - alpha * grad_w
  50. updated_b = current_b - alpha * grad_b
  51. return updated_w, updated_b
  52. # ------------5. 测试:运行梯度下降算法计算最优的w和b-------
  53. w, b, cost_list = grad_desc( data, initial_w, initial_b, alpha, num_iter )
  54. print( "w is: ", w)
  55. print( "b is: ", b)
  56. cost = compute_cost(w, b, data)
  57. print( "cost is: ", cost)
  58. #plt.plot(cost_list)
  59. #plt.show()
  60. # ------------6. 画出拟合曲线-------------------------
  61. plt.scatter(x, y)
  62. # 针对每一个x,计算出预测的y值
  63. pred_y = w * x + b
  64. plt.plot(x, pred_y, c= 'r')
  65. plt.show()

sklearn库实现


    
    
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from sklearn.linear_model import LinearRegression
  4. # -------------1. 数据---------
  5. #points = np.genfromtxt('data.csv', delimiter=',')
  6. data = np.array([[ 32, 31], [ 53, 68], [ 61, 62], [ 47, 71], [ 59, 87], [ 55, 78], [ 52, 79], [ 39, 59], [ 48, 75], [ 52, 71],
  7. [ 45, 55], [ 54, 82], [ 44, 62], [ 58, 75], [ 56, 81], [ 48, 60], [ 44, 82], [ 60, 97], [ 45, 48], [ 38, 56],
  8. [ 66, 83], [ 65, 118], [ 47, 57], [ 41, 51], [ 51, 75], [ 59, 74], [ 57, 95], [ 63, 95], [ 46, 79],
  9. [ 50, 83]])
  10. # 提取points中的两列数据,分别作为x,y
  11. x = data[:, 0]
  12. y = data[:, 1]
  13. # --------------2. 定义损失函数--------------
  14. # 损失函数是系数的函数,另外还要传入数据的x,y
  15. def compute_cost( w, b, data):
  16. total_cost = 0
  17. M = len(data)
  18. # 逐点计算平方损失误差,然后求平均数
  19. for i in range(M):
  20. x = data[i, 0]
  21. y = data[i, 1]
  22. total_cost += (y - w * x - b) ** 2
  23. return total_cost / M
  24. lr = LinearRegression()
  25. x_new = x.reshape(- 1, 1)
  26. y_new = y.reshape(- 1, 1)
  27. lr.fit(x_new, y_new)
  28. # 从训练好的模型中提取系数和偏置
  29. w = lr.coef_[ 0][ 0]
  30. b = lr.intercept_[ 0]
  31. print( "w is: ", w)
  32. print( "b is: ", b)
  33. cost = compute_cost(w, b, data)
  34. print( "cost is: ", cost)
  35. plt.scatter(x, y)
  36. # 针对每一个x,计算出预测的y值
  37. pred_y = w * x + b
  38. plt.plot(x, pred_y, c= 'r')
  39. plt.show()

多元线性回归(sklearn库实现

波士顿房价数据


    
    
  1. import numpy as np
  2. import pandas as pd
  3. from sklearn.linear_model import LinearRegression
  4. from sklearn.model_selection import cross_val_predict, train_test_split
  5. from sklearn import datasets
  6. from sklearn.datasets import fetch_california_housing
  7. #data = fetch_california_housing()
  8. data = datasets.load_boston()
  9. df = pd.DataFrame(data.data, columns=data.feature_names)
  10. target = pd.DataFrame(data.target, columns=[ 'MEDV'])
  11. X = df
  12. y = target
  13. # 数据集划分
  14. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.5, random_state= 1)
  15. print(X_train.shape)
  16. print(X_test.shape)
  17. # 模型训练
  18. lr = LinearRegression()
  19. lr.fit(X_train, y_train)
  20. print(lr.coef_)
  21. print(lr.intercept_)
  22. # 模型评估
  23. y_pred = lr.predict(X_test)
  24. from sklearn import metrics
  25. MSE = metrics.mean_squared_error(y_test, y_pred)
  26. RMSE = np.sqrt(metrics.mean_squared_error(y_test, y_pred))
  27. print( 'MSE:', MSE)
  28. print( 'RMSE:', RMSE)
  29. # -----------图像绘制--------------
  30. import matplotlib.pyplot as plt
  31. import matplotlib as mpl
  32. mpl.rcParams[ 'font.family'] = [ 'sans-serif']
  33. mpl.rcParams[ 'font.sans-serif'] = [ 'SimHei']
  34. mpl.rcParams[ 'axes.unicode_minus']= False
  35. # 绘制图
  36. plt.figure(figsize=( 15, 5))
  37. plt.plot( range( len(y_test)), y_test, 'r', label= '测试数据')
  38. plt.plot( range( len(y_test)), y_pred, 'b', label= '预测数据')
  39. plt.legend()
  40. plt.show()
  41. # # 绘制散点图
  42. plt.scatter(y_test, y_pred)
  43. plt.plot([y_test. min(),y_test. max()], [y_test. min(),y_test. max()], 'k--')
  44. plt.xlabel( '真实值')
  45. plt.ylabel( '预测值')
  46. plt.show()

文章知识点与官方知识档案匹配,可进一步学习相关知识
算法技能树首页概览 58543 人正在系统学习中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值