当前位置: 首页 > 编程笔记 >

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

梁华清
2023-03-14
本文向大家介绍Python 实现3种回归模型(Linear Regression,Lasso,Ridge)的示例,包括了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实现逻辑回归的示例,包括了python实现逻辑回归的示例的使用技巧和注意事项,需要的朋友参考一下 代码 以上就是python实现逻辑回归的示例的详细内容,更多关于python 逻辑回归的资料请关注呐喊教程其它相关文章!

  • 本文向大家介绍带你学习Python如何实现回归树模型,包括了带你学习Python如何实现回归树模型的使用技巧和注意事项,需要的朋友参考一下 所谓的回归树模型其实就是用树形模型来解决回归问题,树模型当中最经典的自然还是决策树模型,它也是几乎所有树模型的基础。虽然基本结构都是使用决策树,但是根据预测方法的不同也可以分为两种。第一种,树上的叶子节点就对应一个预测值和分类树对应,这一种方法称为回归树。第二

  • Logistic回归模型 二项Logistic回归模型(binomial logistic regression model)是一种分类模型,由条件概率分布$$P(Y|X)$$表示,形式为参数化的logistic分布。 一、模型定义 模型是如下的条件概率分布: $$ P(Y=1|X)=\dfrac{e{w\cdot x+b}}{1+e{w\cdot x+b}} $$ $$ P(Y=0|X)=1-P

  • 本文向大家介绍Python基于numpy模块实现回归预测,包括了Python基于numpy模块实现回归预测的使用技巧和注意事项,需要的朋友参考一下 代码如下 上面的一段代码利用numpy生成数据序列,并实现了1阶回归,并画出预测效果图,图形如下: 将代码改一下,实现2阶、3阶回归预测,只需要model = np.polyfit(t, y, deg =2)即可,同理3阶模型就把deg改为3即可。 2

  • 线性回归模型(linear regression) 1.模型定义 给定数据集,$$T={(x{(1)},y{(1)}),(x{(2)},y{(2)}),...,(x{(m)},y{(m)})}$$,其中$$x{(i)}=(1, x_1, x_2, ..., x_n)T\in X= R{n+1}$$,$$y{(i)}\in Y=R$$,线性回归模型试图学到一个通过属性的线性组合来进行预测的函数,即

  • 本文向大家介绍Swift实现“或”操作符的3种方法示例,包括了Swift实现“或”操作符的3种方法示例的使用技巧和注意事项,需要的朋友参考一下 前言 我在看喵神的书的时候,发现书中有个练习(如下图),我觉得挺有意思,就把其中的“||”操作符实现了一下,跟大家分享一下。 使用Swift实现“||”操作符,我发现有三种方式,各自特点如下: 第一种:普通方式 第二种:性能优化 第三种:性能优化+写法优雅