打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
手把手教你Python实现30 个主流机器学习算法

重磅干货,第一时间送达

上周推了一篇关于机器学习算法需要掌握到什么程度的文章
掌握机器学习算法的三种境界,附资源推荐!
第三重境界便是Python实现主流机器学习模型。
今天向大家推荐普林斯顿博士后 David Bourgin 最近开源的项目:用 NumPy 手写所有主流 ML 模型,看了一下,代码可读性极强。

在每一个代码集下,作者都会提供不同实现的参考资料,例如模型的效果示例图、参考论文和参考链接等。
以线性回归为例,作者不但用500行代码实现了OLS/Ridge/Logistic/Bayesian linear regression
import numpy as np
from ..utils.testing import is_symmetric_positive_definite, is_number

class LinearRegression:
    def __init__(self, fit_intercept=True):
        """
        An ordinary least squares regression model fit via the normal equation.
        Parameters

        fit_intercept : bool
            Whether to fit an additional intercept term in addition to the
            model coefficients. Default is True.
        """

        self.beta = None
        self.fit_intercept = fit_intercept
    def fit(self, X, y):
        """
        Fit the regression coefficients via maximum likelihood.
        Parameters
        ----------
        X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)`
            A dataset consisting of `N` examples, each of dimension `M`.
        y : :py:class:`ndarray <numpy.ndarray>` of shape `(N, K)`
            The targets for each of the `N` examples in `X`, where each target
            has dimension `K`.
        """

        # convert X to a design matrix if we're fitting an intercept
        if self.fit_intercept:
            X = np.c_[np.ones(X.shape[0]), X]
        pseudo_inverse = np.dot(np.linalg.inv(np.dot(X.T, X)), X.T)
        self.beta = np.dot(pseudo_inverse, y)
    def predict(self, X):
        """
        Used the trained model to generate predictions on a new collection of
        data points.
        Parameters
       ----------
        X : :py:class:`ndarray <numpy.ndarray>` of shape `(Z, M)`
            A dataset consisting of `Z` new examples, each of dimension `M`.
        Returns
        -------
        y_pred : :py:class:`ndarray <numpy.ndarray>` of shape `(Z, K)`
            The model predictions for the items in `X`.
        """

        # convert X to a design matrix if we're fitting an intercept
        if self.fit_intercept:
            X = np.c_[np.ones(X.shape[0]), X]
        return np.dot(X, self.beta)
还画出了手写与调用sklearn的对比:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
python数据分析基础——numpy和matplotlib
ML之LiR:使用线性回归LiR回归模型在披萨数据集上拟合(train)、价格回归预测(test)
详解如何利用Cython为Python代码加速
用Python实现机器学习算法——Softmax 回归算法
AI算法:逻辑回归原理与实现
Python遇见机器学习 ---- k近邻(kNN)算法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服