机器学习算法——线性回归LinearRegression

线性回归法

思想

  • 解决回归问题
  • 算法可解释性强
  • 一般在坐标轴中:横轴是特征(属性),纵坐标为预测的结果,输出标记(具体数值)

分类问题中,横轴和纵轴都是样本特征属性(肿瘤大小,肿瘤发现时间)
尤尔小屋

问题产生

image.png
  • 求解出拟合的直线y=ax+b
  • 根据样本点x^{(i)},求解预测值\hat y^{(i)}
  • 求解真实值和预测值的差距尽量小 ,通常用差的平方和最小表示,损失函数为:\mathop {min}\sum ^{m}_{i=1} (y^{(i)}-{\hat {y^{(i)}}})^2
    \mathop {min}\sum ^{m}_{i=1} ({y^{i}-ax^{(i)}-b})^2
  • 上面的损失函数loss function实际上就是求解a,b

最小二乘法求解a,b

求解损失函数J(a,b)的过程:J(a,b) = \mathop {min}\sum ^{m}_{i=1} ({y^{i}-ax^{(i)}-b})^2
分别对a,b求导,在令导数为0,进行求解最终结果为:

image.png

  • 先对b求导


    image.png

    image.png
  • 对a求导:


    image.png
image.png

a的另一种表示形式:

image.png

向量化过程

向量化主要是针对a的式子来进行改进,将:分子看做w^{(i)},v^{(i)},分母看做w^{(i)},w^{(i)}

image.png

image.png
import numpy as np

class SimpleLinearRegression1(object):
    def __init__(self):
        # ab不是用户送进来的参数,相当于是私有的属性
        self.a_ = None
        self.b_ = None
    
    def fit(self, x_train,y_train):
        # fit函数:根据训练数据集来得到模型
        assert x_train.ndim == 1, \
            "simple linear regression can only solve single feature training data"
        assert len(x_train) == len(y_train), \
            "the size of x_train must be equal to the size of y_train"

        x_mean = np.mean(x_train)
        y_mean = np.mean(y_train)

        num = 0.0
        d = 0.0
        for x, y in zip(x_train, y_train):
            num += (x - x_mean) * (y - y_mean)
            d += (x - x_mean) ** 2
        
        self.a_ = num / d
        self.b_ = y_mean - self.a_ * x_mean
        
        # 返回自身,sklearn对fit函数的规范
        return self
    
    def predict(self, x_predict):
        # 传进来的是待预测的x 
        assert x_predict.ndim == 1, \
            "simple linear regression can only solve single feature training data"
        assert self.a_ is not None and self.b_ is not None, \
            "must fit before predict!"
            
        return np.array([self._predict(x) for x in x_predict])
    
    def _predict(self, x_single):
        # 对一个数据进行预测 
        return self.a_ * x_single + self.b_
    
    def __repr__(self):
        # 字符串输出
        return "SimpleLinearRegression1()"
    
  
 # 通过向量化实现
class SimpleLinearRegression2(object):
    def __init__(self):
        # a, b不是用户送进来的参数,相当于是私有的属性
        self.a_ = None
        self.b_ = None
    
    def fit(self, x_train, y_train):
        # fit函数:根据训练数据集来得到模型
        assert x_train.ndim == 1, \
            "simple linear regression can only solve single feature training data"
        assert len(x_train) == len(y_train), \
            "the size of x_train must be equal to the size of y_train"

        x_mean = np.mean(x_train)
        y_mean = np.mean(y_train)
        
        #  改成向量形式代替for循环,numpy中的.dot形式
        #  参考上面的向量化公式 
        num = (x_train - x_mean).dot(y_train - y_mean)
        d = (x_train - x_mean).dot(x_train - x_mean)
        
        self.a_ = num / d
        self.b_ = y_mean - self.a_ * x_mean
        
        # 返回自身,sklearn对fit函数的规范
        return self
    
    def predict(self, x_predict):
        # 传进来的是待预测的x 
        assert x_predict.ndim == 1, \
            "simple linear regression can only solve single feature training data"
        assert self.a_ is not None and self.b_ is not None, \
            "must fit before predict!"
            
        return np.array([self._predict(x) for x in x_predict])
    
    def _predict(self, x_single):
        # 对一个数据进行预测 
        return self.a_ * x_single + self.b_
    
    def __repr__(self):
        # 字符串函数,输出方便进行查看
        return "SimpleLinearRegression2()"

衡量标准

衡量标准:将数据分成训练数据集train和测试数据集test,通过训练数据集得到a和b,再通过测试数据集进行衡量

image.png

  • 均方误差MSE,mean squared error,存在量纲问题MSE=\frac {1}{m}\sum ^{m}_{i=1}(y^{(i)}_{test}-\hat y^{(i)}_{test})^2
  • 均方根误差RMSE,root mean squared error,RMSE=\sqrt{MSE_{test}}=\sqrt {\frac {1}{m}\sum ^{m}_{i=1}(y^{(i)}_{test}-\hat y^{(i)}_{test})^2}
  • 平均绝对误差MAE,mean absolute error,MAE=\frac {1}{m}\sum^{m}_{i=1}|y^{(i)}_{test}-\hat y^{(i)}_{test}|

sklearn中没有RMSE,只有MAE、MSE

import numpy as np
from math import sqrt


def accuracy_score(y_true, y_predict):
    '''准确率的封装:计算y_true和y_predict之间的准确率'''
    assert y_true.shape[0] == y_predict.shape[0], \
    "the size of y_true must be equal to the size of y_predict"

    return sum(y_true ==y_predict) / len(y_true)


def mean_squared_error(y_true, y_predict):
    # 计算y_true 和 y_predict之间的MSE
    assert len(y_true) == len(y_predict), \
        "the size of y_true must be equal to the size of y_predict"
    return np.sum((y_true - y_predict)**2) / len(y_true)


def root_mean_squared_error(y_true, y_predict):
    # 计算y_true 和 y_predict之间的RMSE
    return sqrt(mean_squared_error(y_true, y_predict))


def mean_absolute_error(y_true, y_predict):
    # 计算y_true 和 y_predict之间的MAE
    assert len(y_true) == len(y_predict), \
        "the size of y_true must be equal to the size of y_predict"
    
    return np.sum(np.absolute(y_true - y_predict)) / len(y_true)
image.png

R^2指标

R^2指标的定义为
R^2=1- \frac {SS_{residual}}{SS_{total}}
R^2=1-\frac {\sum_i{(\hat y^{(i)}-y^{(i)}})^2}{\sum_i{(\bar y-y^{(i)}})^2}

image.png
image.png

分子为模型预测产生的误差;分母为使用均值产生的误差(baseline model产生的误差)

式子表示为:预测模型没有产生误差的指标

  • R^2 \leq 1
  • R^2越小越好。R^2最大值为1,此时预测模型不犯误差。模型等于基准模型时,R^2为0
  • R^2小于0,此时学习到的模型还不如基准模型,说明数据可能不存在线性关系
  • R^2的另一种表示为R^2=1-\frac {MSE(\hat y,y)}{Var(y)}Var表示方差
image.png

多元线性回归

将特征数从1拓展到了N,求解思路和一元线性回归类似。


image.png

目标函数


image.png
image.png
image.png

image.png

image.png
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容