机器学习-多变量线性回归-详细示例版

2 篇文章 0 订阅
2 篇文章 0 订阅

本文会尽可能详细地解释目前其他网上教程所忽略的原理(重点放在补充他人未说清楚的,或者一带而过的),并给出Java版本的代码实现示例。

 

代价函数求偏导数的过程:

代价函数:

J(\theta_0,\theta_1...\theta_n)=\frac{1}{2m}\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)})^2

即对 (h_\theta(x^{(i)})-y^{(i)})^2 求导(再求和),

其中 ^{(i)} 是求和过程中的标记,因此忽略掉,即:(h_\theta(x)-y)^2

其中 h_\theta(x)=\theta^TX=\theta_0x_0+\theta_1x_1+...+\theta_nx_n

(h_\theta(x)-y)^2 = (\theta_0x_0+\theta_1x_1+...+\theta_nx_n)^2-2y(\theta_0x_0+\theta_1x_1+...+\theta_nx_n)+y^2

 

第一部分求导

关于 \theta_p 求导,先求导 (\theta_0x_0+\theta_1x_1+...+\theta_nx_n)^2 部分,直接忽略掉与 \theta_p 无关的部分

(\theta_0x_0+\theta_1x_1+...+\theta_nx_n)^2 展开之后,与 \theta_p 有关的项是:

\theta_p^2x_p^2+2\theta_px_p(\theta_0x_0+\theta_1x_1+...+\theta_nx_n-\theta_px_p)

求导之后:
2\theta_px_p^2+2x_p(\theta_0x_0+\theta_1x_1+...+\theta_nx_n-\theta_px_p)

2x_p(\theta_px_p+h(x)-\theta_px_p)
2x_ph(x)


第二部分求导
-2y(\theta_0x_0+\theta_1x_1+...+\theta_nx_n) 关于\theta_p 求导,得到

-2yx_p


第三部分求导
y^2求导为 0

 

三部分相加
偏导数为

2x_p(h(x)-y)

 

所以多变量线性回归的批量梯度下降算法为:

\theta_p := \theta_p - \alpha \frac{1}{m}\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)})x_p^{(i)}

 

线性回归Java版本代码

Linear Regression with Multiple Variables

/** 数据集 */
public class TrainingSet {

    public List<Data> dataList = new ArrayList<>();

    public void add(double y, double... x) {
        Data data = new Data();
        data.x = x;
        data.y = y;
        dataList.add(data);
    }

    public static class Data {
        public double[] x;
        public double y;
    }

}
/** 线性回归例子 */
public class LinearRegression {

    /** 添加模拟数据 */
    static void mock(TrainingSet ts, double x1, double x2) {
        // 模拟 y = θ0·x0 + θ1·x1 + θ2·x2
        // 其中 x0 永远为1
        final double θ0 = 3.2, θ1 = 1.5, θ2 = 0.3;
        final double x0 = 1;
        double y = θ0*x0 + θ1*x1 + θ2*x2;
        ts.add(y, x0, x1, x2);
    }

    public static void main(String[] args) {
        TrainingSet ts = new TrainingSet();
        //生成100组模拟数据
        for(int i = 0; i < 100; i++) {
            mock(ts, Math.random(), Math.random());
        }

        LinearRegression lr = new LinearRegression();
        lr.study(ts);
    }


    double[] θ;

    final double alpha = 0.001;

    /** 启动学习 */
    void study(TrainingSet ts) {
        initTheta(ts);
        double costMin = Double.MAX_VALUE;
        while(true) {
            double cost = calculateCost(ts);
            if(cost < costMin) {
                double[] delta = new double[θ.length];
                for(int i = 0; i < θ.length; i++) {
                    delta[i] = calculateDelta(ts, i);
                    System.out.println("delta"+i+" = " + D(delta[i]) + ", cost=" + D(cost) + ", θ"+i+"=" + D(θ[i]));
                }
                for(int i = 0; i < θ.length; i++) {
                    θ[i] = θ[i] - alpha * delta[i];
                }
                costMin = cost;
            } else {
                break;
            }
        }
        System.out.println("本轮学习得到的θ为:" + DA(θ));
    }

    /** 初始化theta */
    void initTheta(TrainingSet ts) {
        if (null == θ) {
            θ = new double[ts.dataList.get(0).x.length];
        }
    }

    /** 预测函数 */
    double hypothesis(double[] x) {
        //return θ[0] * x[0] + θ[1] * x[1] + θ[2] * x[2] + ...;
        double value = 0;
        for (int i = 0;  i < x.length; i++) {
            value += θ[i] * x[i];
        }
        return value;
    }

    /** 计算代价 */
    double calculateCost(TrainingSet ts) {
        // 代价函数 J(θ0,θ1...θn) = Σ[i=1~m](h(x_i) - y_i)² / 2m
        // m 代表 m组数据
        double variance = 0;
        for(TrainingSet.Data data : ts.dataList) {
            variance += Math.pow(hypothesis(data.x) - data.y, 2);
        }
        return variance / (2 * ts.dataList.size());
    }

    /** 计算代价函数的偏导数
     * @param i 对θi求偏导 */
    double calculateDelta(TrainingSet ts, int i) {
        double sum = 0;
        for (TrainingSet.Data data : ts.dataList) {
            sum += 2 * data.x[i] * ( hypothesis(data.x) - data.y );
        }
        return sum;
    }

    static DecimalFormat fmt = new DecimalFormat("#.#####");

    static String D(double val) {
        return fmt.format(val);
    }

    static String DA(double[] vals) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < vals.length; i++) {
            sb.append("θ" + i + " = " + fmt.format(vals[i]) + " , ");
        }
        return sb.toString();
    }
}

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值