公共的抽象基类

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()

测试效果

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

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

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

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

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

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。