python多项式拟合结合lasso回归_Python 实现3种回归模型(Linear Regression,Lasso,Ridge)的示例...

这是一个Python代码示例,展示了如何实现三种回归模型:线性回归、Lasso回归和Ridge回归。每个模型都继承自公共的抽象基类`LinearModel`,并实现了`fit`和`predict`方法。`Lasso`和`Ridge`模型还考虑了正则化,分别使用了L1和L2范数。测试代码中生成了模拟数据并绘制了预测曲线,展示了不同模型的效果。
摘要由CSDN通过智能技术生成

公共的抽象基类

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 实现 回归模型的资料请关注云海天教程其它相关文章!

原文链接:https://www.jianshu.com/p/997e0ee1e010

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值