zoukankan      html  css  js  c++  java
  • 解决异方差问题--加权最小二乘法

    异方差问题 

      Ordinary Least Squares (OLS) 需要四个 - -有些人说五或六个 - 假设要满足,但建模时我们经常会遇到异方差(Heteroskedasticity)问题,

    那是因为,很多数据都表现出这种“异方差性”。我们通常可以直观地解释原因: 

    • 随着年龄的增长,净值往往会出现分歧
    • 随着公司规模的扩大,收入趋于分化
    • 或者,随着婴儿身高的增加,体重趋于分散

      OLS的主要假设之一是数据的残差相同的,当不满足同方差的假设时,即存在异方差时候,我们需要另外的方法--加权最小二乘法(WLS)去处理。

    WLS实例 

    import numpy as np
    import pandas as pd
    import seaborn as sns
    import statsmodels.api as sm
    
    # generate random data
    np.random.seed(24)
    x = np.random.uniform(-5,5,25)
    e= 2*np.random.randn(25)
    y = 2*x+e
    # alternate error as a function of x
    e2 = e*(x+5)
    y2 = 2*x+e2
    
    sns.regplot(x,y);
    sns.regplot(x,y2);

       可以看到,这些集合来自相同的实例函数,但是作为x的函数的增加的方差导致橙色模型拟合不同于蓝色的线。 在另一个随机抽取中,斜率可能低于蓝色,但一般会更加不稳定。

    # add a strong outlier for high x
    x_high = np.append(x,5)
    y_high = np.append(y2,160)
    # add a strong outlier for low x
    x_low = np.append(x,-4)
    y_low = np.append(y2,160)
    
    sns.regplot(x_high,y_high);

    sns.regplot(x_low,y_low);

      上面的第一个附加模仿了一个常见的情况,即高方差区域(预期)会看到极端观察。 这将比WLS更多地影响OLS,因为WLS将减去方差及其“惩罚”。

      计算样本权重,我们添加的错误随(x + 5)的变化而变化; 我们可以使用它来对值进行反向加权。

    # calculate weights for sets with low and high outlier
    sample_weights_low = [1/(x+5) for x in x_low]
    sample_weights_high = [1/(x+5) for x in x_high]
    # reshape for compatibility
    X_low = x_low.reshape(-1, 1)
    X_high = x_high.reshape(-1, 1)
    
    # import and fit an OLS model, check coefficients
    from sklearn.linear_model import LinearRegression
    model = LinearRegression()
    model.fit(X_low, y_low)
    # fit WLS using sample_weights
    WLS = LinearRegression()
    WLS.fit(X_low, y_low, sample_weight=sample_weights_low)
    print(model.intercept_, model.coef_)
    print('WLS')
    print(WLS.intercept_, WLS.coef_)
    

      需要注意的是,WLS中的斜率受到低异常值的影响。 低区域应该具有低可变性,因此异常值被放大到高于OLS的范围,推动斜率更负。 让我们看下面如何在WLS中抑制高异常值。 

    model = LinearRegression()
    model.fit(X_high, ymod)
    WLS.fit(X_high, ymod, sample_weight=sample_weights_high)
    print(model.intercept_, model.coef_)
    print('WLS')
    print(WLS.intercept_, WLS.coef_)

    总结

      这是WLS的一个基本介绍,在这个领域还有很多东西要探索。例如:在建模时始终寻求使用经验或先验信息。使用模型的残差 - 例如,如果var(εi)=σ2x_i* var(εi)=σ2x_i  那么我们可以决定使用w_i = 1 / x_i。

      如果响应是n观察的平均值,则类似var(y_i)= var(ε_i)=σ2/ n_i * var(y_i)= var(ε_i)=σ2/ n_i,那么我们可以决定使用w_i = n_i。
    有时我们知道异方差的类型。在这种情况下,我们可能决定使用权重与测量误差的方差成反比。

  • 相关阅读:
    Lintcode: Two Strings Are Anagrams
    Leetcode: House Robber
    Leetcode: Binary Tree Right Side View
    Leetcode: Number of Islands
    Lintcode: Subarray Sum
    Lintcode: Sort Letters by Case
    Lintcode: Sort Colors II
    Lintcode: Single Number III
    Lintcode: Search Range in Binary Search Tree
    Lintcode: Binary Tree Serialization (Serialization and Deserialization Of Binary Tree)
  • 原文地址:https://www.cnblogs.com/jin-liang/p/9537539.html
Copyright © 2011-2022 走看看