Python 实现3种回归模型(Linear Regression,Lasso,Ridge)的示例

 更新时间:2020年10月15日 10:43:27   作者:农大鲁迅  
这篇文章主要介绍了Python 实现 3 种回归模型(Linear Regression,Lasso,Ridge)的示例,帮助大家更好的进行机器学习,感兴趣的朋友可以了解下

公共的抽象基类

import numpy as np
from abc import ABCMeta, abstractmethod


class LinearModel(metaclass=ABCMeta):
 """
 Abstract base class of Linear Model.
 """

 def __init__(self):
  # Before fit or predict, please transform samples' mean to 0, var to 1.
  self.scaler = StandardScaler()

 @abstractmethod
 def fit(self, X, y):
  """fit func"""

 def predict(self, X):
  # before predict, you must run fit func.
  if not hasattr(self, 'coef_'):
   raise Exception('Please run `fit` before predict')

  X = self.scaler.transform(X)
  X = np.c_[np.ones(X.shape[0]), X]

  # `x @ y` == `np.dot(x, y)`
  return X @ self.coef_

Linear Regression

class LinearRegression(LinearModel):
 """
 Linear Regression.
 """

 def __init__(self):
  super().__init__()

 def fit(self, X, y):
  """
  :param X_: shape = (n_samples + 1, n_features)
  :param y: shape = (n_samples])
  :return: self
  """
  self.scaler.fit(X)
  X = self.scaler.transform(X)
  X = np.c_[np.ones(X.shape[0]), X]
  self.coef_ = np.linalg.inv(X.T @ X) @ X.T @ y
  return self

Lasso

class Lasso(LinearModel):
 """
 Lasso Regression, training by Coordinate Descent.
 cost = ||X @ coef_||^2 + alpha * ||coef_||_1
 """
 def __init__(self, alpha=1.0, n_iter=1000, e=0.1):
  self.alpha = alpha
  self.n_iter = n_iter
  self.e = e
  super().__init__()

 def fit(self, X, y):
  self.scaler.fit(X)
  X = self.scaler.transform(X)
  X = np.c_[np.ones(X.shape[0]), X]
  self.coef_ = np.zeros(X.shape[1])
  for _ in range(self.n_iter):
   z = np.sum(X * X, axis=0)
   tmp = np.zeros(X.shape[1])
   for k in range(X.shape[1]):
    wk = self.coef_[k]
    self.coef_[k] = 0
    p_k = X[:, k] @ (y - X @ self.coef_)
    if p_k < -self.alpha / 2:
     w_k = (p_k + self.alpha / 2) / z[k]
    elif p_k > self.alpha / 2:
     w_k = (p_k - self.alpha / 2) / z[k]
    else:
     w_k = 0
    tmp[k] = w_k
    self.coef_[k] = wk
   if np.linalg.norm(self.coef_ - tmp) < self.e:
    break
   self.coef_ = tmp
  return self

Ridge

class Ridge(LinearModel):
 """
 Ridge Regression.
 """

 def __init__(self, alpha=1.0):
  self.alpha = alpha
  super().__init__()

 def fit(self, X, y):
  """
  :param X_: shape = (n_samples + 1, n_features)
  :param y: shape = (n_samples])
  :return: self
  """
  self.scaler.fit(X)
  X = self.scaler.transform(X)
  X = np.c_[np.ones(X.shape[0]), X]
  self.coef_ = np.linalg.inv(
   X.T @ X + self.alpha * np.eye(X.shape[1])) @ X.T @ y
  return self

测试代码

import matplotlib.pyplot as plt
import numpy as np

def gen_reg_data():
 X = np.arange(0, 45, 0.1)
 X = X + np.random.random(size=X.shape[0]) * 20
 y = 2 * X + np.random.random(size=X.shape[0]) * 20 + 10
 return X, y

def test_linear_regression():
 clf = LinearRegression()
 X, y = gen_reg_data()
 clf.fit(X, y)
 plt.plot(X, y, '.')
 X_axis = np.arange(-5, 75, 0.1)
 plt.plot(X_axis, clf.predict(X_axis))
 plt.title("Linear Regression")
 plt.show()

def test_lasso():
 clf = Lasso()
 X, y = gen_reg_data()
 clf.fit(X, y)
 plt.plot(X, y, '.')
 X_axis = np.arange(-5, 75, 0.1)
 plt.plot(X_axis, clf.predict(X_axis))
 plt.title("Lasso")
 plt.show()

def test_ridge():
 clf = Ridge()
 X, y = gen_reg_data()
 clf.fit(X, y)
 plt.plot(X, y, '.')
 X_axis = np.arange(-5, 75, 0.1)
 plt.plot(X_axis, clf.predict(X_axis))
 plt.title("Ridge")
 plt.show()

测试效果

更多机器学习代码,请访问 https://github.com/WiseDoge/plume

以上就是Python 实现 3 种回归模型(Linear Regression,Lasso,Ridge)的示例的详细内容,更多关于Python 实现 回归模型的资料请关注脚本之家其它相关文章!

相关文章

  • Python locust工具使用详解

    Python locust工具使用详解

    这篇文章主要介绍了Python locust工具使用详解,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-03-03
  • 国产麒麟系统kylin部署python项目详细步骤

    国产麒麟系统kylin部署python项目详细步骤

    这篇文章主要给大家介绍了关于国产麒麟系统kylin部署python项目的相关资料,文中通过代码示例介绍的非常详细,对大家的学习或者工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-09-09
  • tensorflow2.0的函数签名与图结构(推荐)

    tensorflow2.0的函数签名与图结构(推荐)

    这篇文章主要介绍了tensorflow2.0的函数签名与图结构,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-04-04
  • 将python文件打包成EXE应用程序的方法

    将python文件打包成EXE应用程序的方法

    相信大家都想把自己完成的项目打包成EXE应用文件,然后就可以放在桌面随时都能运行了,下面来分享利用pytinstaller这个第三方库来打包程序,感兴趣的朋友跟随小编一起看看吧
    2019-05-05
  • python使用datetime模块处理日期时间及常用功能详解

    python使用datetime模块处理日期时间及常用功能详解

    datetime模块是Python标准库中用于处理日期和时间的模块,在本节中,我们将介绍datetime模块的一些常用功能,并通过实例代码详细讲解每个知识点,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2023-06-06
  • Python基础中的的if-else语句详解

    Python基础中的的if-else语句详解

    这篇文章主要为大家详细介绍了Python基础中的的if-else语句,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-02-02
  • 深入解析python中的实例方法、类方法和静态方法

    深入解析python中的实例方法、类方法和静态方法

    这篇文章主要介绍了python中的实例方法、类方法和静态方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • 解决tensorflow训练时内存持续增加并占满的问题

    解决tensorflow训练时内存持续增加并占满的问题

    今天小编就为大家分享一篇解决tensorflow训练时内存持续增加并占满的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • Python画图练习案例分享

    Python画图练习案例分享

    这篇文章主要介绍了Python画图练习案例分享,文章基于Python实现各种画图,具有一定的参考价值,感兴趣的小伙伴可以参考一下
    2022-07-07
  • 使用C语言来扩展Python程序和Zope服务器的教程

    使用C语言来扩展Python程序和Zope服务器的教程

    这篇文章主要介绍了使用C语言来扩展Python程序和Zope服务器的教程,本文来自于IBM官方网站技术文档,需要的朋友可以参考下
    2015-04-04

最新评论