代码来源:https://github.com/eriklindernoren/ML-From-Scratch

首先定义一个基本的回归类,作为各种回归方法的基类:

  1. class Regression(object):
  2. """ Base regression model. Models the relationship between a scalar dependent variable y and the independent
  3. variables X.
  4. Parameters:
  5. -----------
  6. n_iterations: float
  7. The number of training iterations the algorithm will tune the weights for.
  8. learning_rate: float
  9. The step length that will be used when updating the weights.
  10. """
  11. def __init__(self, n_iterations, learning_rate):
  12. self.n_iterations = n_iterations
  13. self.learning_rate = learning_rate
  14.  
  15. def initialize_wights(self, n_features):
  16. """ Initialize weights randomly [-1/N, 1/N] """
  17. limit = 1 / math.sqrt(n_features)
  18. self.w = np.random.uniform(-limit, limit, (n_features, ))
  19.  
  20. def fit(self, X, y):
  21. # Insert constant ones for bias weights
  22. X = np.insert(X, 0, 1, axis=1)
  23. self.training_errors = []
  24. self.initialize_weights(n_features=X.shape[1])
  25.  
  26. # Do gradient descent for n_iterations
  27. for i in range(self.n_iterations):
  28. y_pred = X.dot(self.w)
  29. # Calculate l2 loss
  30. mse = np.mean(0.5 * (y - y_pred)**2 + self.regularization(self.w))
  31. self.training_errors.append(mse)
  32. # Gradient of l2 loss w.r.t w
  33. grad_w = -(y - y_pred).dot(X) + self.regularization.grad(self.w)
  34. # Update the weights
  35. self.w -= self.learning_rate * grad_w
  36.  
  37. def predict(self, X):
  38. # Insert constant ones for bias weights
  39. X = np.insert(X, 0, 1, axis=1)
  40. y_pred = X.dot(self.w)
  41. return y_pred

说明:初始化时传入两个参数,一个是迭代次数,另一个是学习率。initialize_weights()用于初始化权重。fit()用于训练。需要注意的是,对于原始的输入X,需要将其最前面添加一项为偏置项。predict()用于输出预测值。

接下来是简单线性回归,继承上面的基类:

  1. class LinearRegression(Regression):
  2. """Linear model.
  3. Parameters:
  4. -----------
  5. n_iterations: float
  6. The number of training iterations the algorithm will tune the weights for.
  7. learning_rate: float
  8. The step length that will be used when updating the weights.
  9. gradient_descent: boolean
  10. True or false depending if gradient descent should be used when training. If
  11. false then we use batch optimization by least squares.
  12. """
  13. def __init__(self, n_iterations=100, learning_rate=0.001, gradient_descent=True):
  14. self.gradient_descent = gradient_descent
  15. # No regularization
  16. self.regularization = lambda x: 0
  17. self.regularization.grad = lambda x: 0
  18. super(LinearRegression, self).__init__(n_iterations=n_iterations,
  19. learning_rate=learning_rate)
  20. def fit(self, X, y):
  21. # If not gradient descent => Least squares approximation of w
  22. if not self.gradient_descent:
  23. # Insert constant ones for bias weights
  24. X = np.insert(X, 0, 1, axis=1)
  25. # Calculate weights by least squares (using Moore-Penrose pseudoinverse)
  26. U, S, V = np.linalg.svd(X.T.dot(X))
  27. S = np.diag(S)
  28. X_sq_reg_inv = V.dot(np.linalg.pinv(S)).dot(U.T)
  29. self.w = X_sq_reg_inv.dot(X.T).dot(y)
  30. else:
  31. super(LinearRegression, self).fit(X, y)

这里使用两种方式进行计算。如果规定gradient_descent=True,那么使用随机梯度下降算法进行训练,否则使用标准方程法进行训练。

最后是使用:

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. from sklearn.datasets import make_regression
  5. import sys
  6. sys.path.append("/content/drive/My Drive/learn/ML-From-Scratch/")
  7.  
  8. from mlfromscratch.utils import train_test_split, polynomial_features
  9. from mlfromscratch.utils import mean_squared_error, Plot
  10. from mlfromscratch.supervised_learning import LinearRegression
  11.  
  12. def main():
  13.  
  14. X, y = make_regression(n_samples=100, n_features=1, noise=20)
  15.  
  16. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)
  17.  
  18. n_samples, n_features = np.shape(X)
  19.  
  20. model = LinearRegression(n_iterations=100)
  21.  
  22. model.fit(X_train, y_train)
  23.  
  24. # Training error plot
  25. n = len(model.training_errors)
  26. training, = plt.plot(range(n), model.training_errors, label="Training Error")
  27. plt.legend(handles=[training])
  28. plt.title("Error Plot")
  29. plt.ylabel('Mean Squared Error')
  30. plt.xlabel('Iterations')
  31. plt.savefig("test1.png")
  32. plt.show()
  33.  
  34. y_pred = model.predict(X_test)
  35. mse = mean_squared_error(y_test, y_pred)
  36. print ("Mean squared error: %s" % (mse))
  37.  
  38. y_pred_line = model.predict(X)
  39.  
  40. # Color map
  41. cmap = plt.get_cmap('viridis')
  42.  
  43. # Plot the results
  44. m1 = plt.scatter(366 * X_train, y_train, color=cmap(0.9), s=10)
  45. m2 = plt.scatter(366 * X_test, y_test, color=cmap(0.5), s=10)
  46. plt.plot(366 * X, y_pred_line, color='black', linewidth=2, label="Prediction")
  47. plt.suptitle("Linear Regression")
  48. plt.title("MSE: %.2f" % mse, fontsize=10)
  49. plt.xlabel('Day')
  50. plt.ylabel('Temperature in Celcius')
  51. plt.legend((m1, m2), ("Training data", "Test data"), loc='lower right')
  52. plt.savefig("test2.png")
  53. plt.show()
  54.  
  55. if __name__ == "__main__":
  56. main()

利用sklearn库生成线性回归数据,然后将其拆分为训练集和测试集。

utils下的mean_squared_error():

  1. def mean_squared_error(y_true, y_pred):
  2. """ Returns the mean squared error between y_true and y_pred """
  3. mse = np.mean(np.power(y_true - y_pred, 2))
  4. return mse

结果:

Mean squared error: 532.3321383700828

python实现线性回归之简单回归的更多相关文章

  1. 机器学习经典算法具体解释及Python实现--线性回归(Linear Regression)算法

    (一)认识回归 回归是统计学中最有力的工具之中的一个. 机器学习监督学习算法分为分类算法和回归算法两种,事实上就是依据类别标签分布类型为离散型.连续性而定义的. 顾名思义.分类算法用于离散型分布预測, ...

  2. python实现线性回归

    参考:<机器学习实战>- Machine Learning in Action 一. 必备的包 一般而言,这几个包是比较常见的: • matplotlib,用于绘图 • numpy,数组处 ...

  3. python求线性回归斜率

    一. 先说我对这个题目的理解 直线的x,y方程是这样的:y = kx+b, k就是斜率. 求线性回归斜率, 就是说 有这么一组(x, y)的对应值——样本.如果有四组,就说样本量是4.根据这些样本,做 ...

  4. 吴裕雄 python 机器学习——线性回归模型

    import numpy as np from sklearn import datasets,linear_model from sklearn.model_selection import tra ...

  5. python模拟线性回归的点

    构造符合线性回归的数据点 import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 随机生成1000个点 ...

  6. python机器学习---线性回归案例和KNN机器学习案例

    散点图和KNN预测 一丶案例引入 # 城市气候与海洋的关系研究 # 导包 import numpy as np import pandas as pd from pandas import Serie ...

  7. Python机器学习/LinearRegression(线性回归模型)(附源码)

    LinearRegression(线性回归) 2019-02-20  20:25:47 1.线性回归简介 线性回归定义: 百科中解释 我个人的理解就是:线性回归算法就是一个使用线性函数作为模型框架($ ...

  8. 机器学习之线性回归(纯python实现)][转]

    本文转载自:https://juejin.im/post/5a924df16fb9a0634514d6e1 机器学习之线性回归(纯python实现) 线性回归是机器学习中最基本的一个算法,大部分算法都 ...

  9. 【机器学习】线性回归python实现

    线性回归原理介绍 线性回归python实现 线性回归sklearn实现 这里使用python实现线性回归,没有使用sklearn等机器学习框架,目的是帮助理解算法的原理. 写了三个例子,分别是单变量的 ...

随机推荐

  1. iOS 真机查看沙盒目录

    iExplorer 的方法试的时候设备都无法检测到,建议放弃 启用iTunes文件共享,才能够看沙盒内的文件,只需要在plist文件中添加如下信息: <key>UIFileSharingE ...

  2. spring boot 装载自定义yml文件

    yml格式的配置文件感觉很人性化,所以想把项目中的.properties都替换成.yml文件,蛋疼的是springboot自1.5以后就把@configurationProperties中的locat ...

  3. python 开发工具简介

    一.python 开发工具简介 1.IDLE IDLE是开发python程序的基本IDE(集成开发环境),具备基本的IDE的功能,是非商业Python开发的不错的选择.当安装好python以后,IDL ...

  4. 运行npm安装wepy2踩坑error EEXIST 问题

    windows 10安装wepy2 以前用过wepy1,现在要学习wepy2,运行以下命令出错 npm install @wepy/cli -g # 全局安装 WePY CLI 工具 打开log文件, ...

  5. IntelliJ IDEA 激活码 [已购买,分享给码友]

    一.前言 笔者在网上找了一圈,各种方法都试过了,之前那种在网上随便找个注册码,过了一段时间就被封了,想了想还是经常用的和朋友一起购买了,方便日后使用 二.下载最新的 IDEA 其实也可以从老版本直接升 ...

  6. stm32:简单按键输入实现

    开发环境keil4,芯片STM32F103C8T6 1.main.c //串口实验 #include "sys.h" #include "delay.h" #i ...

  7. Go语言笔记 (2) 变量命名与多重赋值

    变量命名 1.大小写 观摩以下代码: func main() { var m int = "你" var M int = "我" fmt.Println(m,M ...

  8. 搭建mariadb数据库系统《一》

                                                                     搭建mariadb数据库系统 案例3:搭建mariadb数据库系统 3 ...

  9. hacknos-player靶机渗透

    靶机下载地址https://www.vulnhub.com/entry/hacknos-player,459/ 网络配置 该靶机可能会存在无法自动分配IP的情况,所以无法扫描到的情况下需要手动配置获取 ...

  10. android注册验证码的使用

    主要是创建了验证码的生成类. 通过此生成类,与imageview相互联系起来,实现验证码显示.并添加点击事件,实现验证码的切换. 实验的截图如下:(验证码可以点击切换) 具体的关于验证码的生成类如下: ...