机器学习(五) 线性回归法 (下)

六、最好的衡量线性回归法的指标: R Squared

 

def r2_score(y_true, y_predict):
    """计算y_true和y_predict之间的R Square"""

    return 1 - mean_squared_error(y_true, y_predict)/np.var(y_true)

 

 

七、多元线性回归

 

 

 

 

 

 

 

 八、实现多元线性回归

 

LinearRegression.py
import numpy as np
from .metrics import r2_score


class LinearRegression:

    def __init__(self):
        """初始化Linear Regression模型"""
        self.coef_ = None
        self.intercept_ = None
        self._theta = None

    def fit_normal(self, X_train, y_train):
        """根据训练数据集X_train, y_train训练Linear Regression模型"""
        assert X_train.shape[0] == y_train.shape[0], \
            "the size of X_train must be equal to the size of y_train"

        X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
        self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)

        self.intercept_ = self._theta[0]
        self.coef_ = self._theta[1:]

        return self

    def predict(self, X_predict):
        """给定待预测数据集X_predict,返回表示X_predict的结果向量"""
        assert self.intercept_ is not None and self.coef_ is not None, \
            "must fit before predict!"
        assert X_predict.shape[1] == len(self.coef_), \
            "the feature number of X_predict must be equal to X_train"

        X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
        return X_b.dot(self._theta)

    def score(self, X_test, y_test):
        """根据测试数据集 X_test 和 y_test 确定当前模型的准确度"""

        y_predict = self.predict(X_test)
        return r2_score(y_test, y_predict)

    def __repr__(self):
        return "LinearRegression()"

 

九、使用 scikit-learn 解决回归问题

 

 十、线性回归的可解释性和更多的思考

 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字? 写了这么多,怎么还不够150字?

  我写的文章只是我自己对bobo老师讲课内容的理解和整理,也只是我自己的弊见。bobo老师的课 是慕课网出品的。欢迎大家一起学习。

posted @ 2018-08-27 21:20  日月山川  阅读(389)  评论(0编辑  收藏  举报