斯坦福大学-线性回归_Exercise Code

本文深入探讨了线性回归的基本概念、实现方法及在实际数据集上的应用案例,包括使用梯度下降法优化参数,并通过网格搜索找到最优参数组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.  线性回归   Linear Regression  

http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=DeepLearning&doc=exercises/ex2/ex2.html

% Exercise 2 Linear Regression

% Data is roughly based on 2000 CDC growth figures
% for boys
%
% x refers to a boy's age
% y is a boy's height in meters
%

clear all; close all; clc
x = load('ex2x.dat'); y = load('ex2y.dat');

m = length(y); % number of training examples


% Plot the training data
figure; % open a new figure window
plot(x, y, 'o');
ylabel('Height in meters')
xlabel('Age in years')

% Gradient descent
x = [ones(m, 1) x]; % Add a column of ones to x
theta = zeros(size(x(1,:)))'; % initialize fitting parameters
MAX_ITR = 1500;
alpha = 0.07;

for num_iterations = 1:MAX_ITR
    % This is a vectorized version of the 
    % gradient descent update formula
    % It's also fine to use the summation formula from the videos
    
    % Here is the gradient
    grad = (1/m).* x' * ((x * theta) - y);
    
    % Here is the actual update
    theta = theta - alpha .* grad;
    
    % Sequential update: The wrong way to do gradient descent
    % grad1 = (1/m).* x(:,1)' * ((x * theta) - y);
    % theta(1) = theta(1) + alpha*grad1;
    % grad2 = (1/m).* x(:,2)' * ((x * theta) - y);
    % theta(2) = theta(2) + alpha*grad2;
end
% print theta to screen
theta

% Plot the linear fit
hold on; % keep previous plot visible
plot(x(:,2), x*theta, '-')
legend('Training data', 'Linear regression')
hold off % don't overlay any more plots on this figure

% Closed form solution for reference
% You will learn about this method in future videos
exact_theta = (x' * x)\x' * y

% Predict values for age 3.5 and 7
predict1 = [1, 3.5] *theta
predict2 = [1, 7] * theta


% Calculate J matrix

% Grid over which we will calculate J
theta0_vals = linspace(-3, 3, 100);
theta1_vals = linspace(-1, 1, 100);

% initialize J_vals to a matrix of 0's
J_vals = zeros(length(theta0_vals), length(theta1_vals));

for i = 1:length(theta0_vals)
	  for j = 1:length(theta1_vals)
	  t = [theta0_vals(i); theta1_vals(j)];    
	  J_vals(i,j) = (0.5/m) .* (x * t - y)' * (x * t - y);
    end
end

% Because of the way meshgrids work in the surf command, we need to 
% transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';
% Surface plot
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0'); ylabel('\theta_1');

% Contour plot
figure;
% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 2, 15))
xlabel('\theta_0'); ylabel('\theta_1');


### 线性回归基础知识与入门教程 线性回归是一种用于建模特征(自变量)和响应变量(因变量)之间线性关系的方法[^4]。它广泛应用于数据分析和机器学习领域,能够帮助我们理解和预测连续型目标变量。 #### 1. 基本概念 简单线性回归涉及单个输入变量 \(x\) 和输出变量 \(y\) 的关系,通常表示为: \[ y = w_1x + b \] 其中 \(w_1\) 是权重(斜率),\(b\) 是偏置项(截距)。对于多个输入变量的情况,则扩展为多元线性回归形式: \[ y = w_1x_1 + w_2x_2 + \dots + w_nx_n + b \] 如果存在非线性关系,可以通过引入高次幂或其他变换来拟合更复杂的模式,例如二次项或三次项的关系[^1]。 #### 2. 使用 Python 实现线性回归 `scikit-learn` 提供了一个强大的工具 `LinearRegression()` 来快速构建线性回归模型。以下是基本用法示例: ```python from sklearn.linear_model import LinearRegression import numpy as np # 创建样本数据 X = np.array([[1], [2], [3], [4], [5]]) y = np.array([2, 4, 6, 8, 10]) # 初始化并训练模型 model = LinearRegression() model.fit(X, y) # 输出回归系数和截距 print(f"回归系数: {model.coef_[0]}") # 回归系数对应于 w1 print(f"截距: {model.intercept_}") # 截距对应于 b ``` 通过上述代码,我们可以轻松获取模型的参数,并进一步利用这些参数进行预测操作。 #### 3. 学习资源推荐 为了深入掌握线性回归的知识体系,建议参考 Andrew Ng 教授在斯坦福大学开设的《Machine Learning》课程[^2]。该课程不仅涵盖了理论基础,还包括实际案例的应用方法,非常适合初学者逐步提升自己的技能水平。 此外,《Python从零到壹》系列文章也提供了详尽的内容梳理,特别是关于回归分析的部分,包含了大量实例说明以及代码演示。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值