机器学习代码分析之一线性回归

xiaoxiao2021-02-28  108

机器学习代码分析之一线性回归

机器学习线性回归中几个重要的函数:

1.CostFunction()损失函数,我们线性回归的目的就是使这个损失函数的值最小。 J = sum((X * theta - y).^2) / (2*m); 2.gradientDescent()梯度下降算法。梯度下降算法是为了求解合适的theta值,从而使CostFunction()的值最小。 for iter = 1:num_iters theta(1) = theta(1) - alpha / m * sum(X * theta_s - y); theta(2) = theta(2) - alpha / m * sum((X * theta_s - y) .* X(:,2)); % 必须同时更新 theta_s=theta; end 3.以上的两个方法可以解决y=theta(0)+theta(1)*x 的线性方程。如果我们的**特征**点很多的时候,我们还可以使用正规方程(normal equation)去求解theta值。这里给出梯度下降和正规方程(normal equation)求解theta值的公式: 这两个方法都可以计算theta的值。使用的场景有所不同,当我们的样本数量在10^3左右时,我们选择正规方程(normal equation)去求解。其次正规方程不需要迭代,也不需要设置alpha(学习速率)。 a.多特征时的梯度下降算法gradientDescentMulti(): for iter = 1:num_iters theta = theta - alpha / m * X' * (X * theta - y); J_history(iter) = computeCostMulti(X, y, theta); end b.多特征时的正规方程(normal equation)normalEqn(): theta = pinv( X' * X ) * X' * y;

这里给出完整的工程代码 http://download.csdn.net/download/qq_18884487/9959854 里面包含了8个工程代码。出自斯坦福大学机器学习讲课代码。

转载请注明原文地址: https://www.6miu.com/read-70244.html

最新回复(0)