欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 實現(xiàn)3種回歸模型(Linear Regression,Lasso,Ridge)的示例

 更新時間:2020年10月15日 10:43:27   作者:農(nóng)大魯迅  
這篇文章主要介紹了Python 實現(xiàn) 3 種回歸模型(Linear Regression,Lasso,Ridge)的示例,幫助大家更好的進(jìn)行機(jī)器學(xué)習(xí),感興趣的朋友可以了解下

公共的抽象基類

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

測試效果

更多機(jī)器學(xué)習(xí)代碼,請訪問 https://github.com/WiseDoge/plume

以上就是Python 實現(xiàn) 3 種回歸模型(Linear Regression,Lasso,Ridge)的示例的詳細(xì)內(nèi)容,更多關(guān)于Python 實現(xiàn) 回歸模型的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python結(jié)合Sprak實現(xiàn)計算曲線與X軸上方的面積

    Python結(jié)合Sprak實現(xiàn)計算曲線與X軸上方的面積

    這篇文章主要介紹了Python結(jié)合Sprak實現(xiàn)計算曲線與X軸上方的面積,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-02-02
  • Python中的閉包

    Python中的閉包

    這篇文章主要介紹了Python中的閉包,閉包在函數(shù)中提出的概念,簡單來說就是一個函數(shù)定義中引用了函數(shù)外定義的變量,并且該函數(shù)可以在其定義環(huán)境外被執(zhí)行。這樣的一個函數(shù)我們稱之為閉包,下面我們一起來看看文章內(nèi)容的具體介紹
    2021-11-11
  • 關(guān)于python的mmh3庫安裝以及使用詳解

    關(guān)于python的mmh3庫安裝以及使用詳解

    這篇文章主要介紹了關(guān)于python的mmh3庫安裝以及使用詳解,哈希方法主要有MD、SHA、Murmur、CityHash、MAC等幾種方法,mmh3全程murmurhash3,是一種非加密的哈希算法,常用于hadoop等分布式存儲情境中,需要的朋友可以參考下
    2023-07-07
  • Python常用編碼的區(qū)別介紹

    Python常用編碼的區(qū)別介紹

    這篇文章介紹了Python常用編碼的區(qū)別,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • Pandas?篩選和刪除目標(biāo)值所在的行的實現(xiàn)

    Pandas?篩選和刪除目標(biāo)值所在的行的實現(xiàn)

    本文主要介紹了Pandas篩選和刪除目標(biāo)值所在的行的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • 使用Python爬取Json數(shù)據(jù)的示例代碼

    使用Python爬取Json數(shù)據(jù)的示例代碼

    這篇文章主要介紹了使用Python爬取Json數(shù)據(jù)的示例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • Python traceback模塊獲取異常信息的使用

    Python traceback模塊獲取異常信息的使用

    Python的traceback模塊提供了多種方法來獲取和展示異常的堆棧信息,本文主要介紹了Python traceback模塊獲取異常信息的使用,具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • python批量修改文件名的實現(xiàn)代碼

    python批量修改文件名的實現(xiàn)代碼

    這篇文章主要介紹了python批量修改文件名的實現(xiàn)代碼,需要的朋友可以參考下
    2014-09-09
  • Python Sphinx使用實例及問題解決

    Python Sphinx使用實例及問題解決

    這篇文章主要介紹了Python Sphinx使用實例及問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • 注意import和from import 的區(qū)別及說明

    注意import和from import 的區(qū)別及說明

    這篇文章主要介紹了注意import和from import 的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09

最新評論