前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >手把手教你Python实现30 个主流机器学习算法

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

作者头像
统计学家
发布2019-09-17 14:56:41
7880
发布2019-09-17 14:56:41
举报
文章被收录于专栏:机器学习与统计学

上周推了一篇关于机器学习算法需要掌握到什么程度的文章

掌握机器学习算法的三种境界,附资源推荐!

第三重境界便是Python实现主流机器学习模型。

今天向大家推荐普林斯顿博士后 David Bourgin 最近开源的项目:用 NumPy 手写所有主流 ML 模型,看了一下,代码可读性极强。

在每一个代码集下,作者都会提供不同实现的参考资料,例如模型的效果示例图、参考论文和参考链接等。

以线性回归为例,作者不但用500行代码实现了OLS/Ridge/Logistic/Bayesian linear regression

代码语言:javascript
复制
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[]), 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[]), X]
        return np.dot(X, self.beta)

还画出了手写与调用sklearn的对比:

更多精彩内容,值得大家仔细挖掘,相信跟着完整实现一遍之后,大家对机器学习基础的掌握也将极其牢固。另外,建议大家配合作者提供的documentation 一同食用,效果更佳。

项目地址:https://github.com/ddbourgin/numpy-ml

文档地址:https://numpy-ml.readthedocs.io/

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-09-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 机器学习与统计学 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档