线性回归--Octave实现

题目为:使用有多个变量的线性回归来预测房屋的价格。ex1data2.txt 房屋价格的训练集. 第一列为房屋面积,第二列为房屋中的房间数量,第三列为实际的价格。

预测X_p=[1650 3];的价格

方法一:采用梯度下降法

1. 首先由于x1和x2相差太多,所以需要使用feature scalling. 这里采用mean derivation. 或者是max-min

function [X_norm, mu, sigma] = featureNormalize(X)
%FEATURENORMALIZE Normalizes the features in X 
%   FEATURENORMALIZE(X) returns a normalized version of X where
%   the mean value of each feature is 0 and the standard deviation
%   is 1. This is often a good preprocessing step to do when
%   working with learning algorithms.

% You need to set these values correctly
X_norm = X;
disp(size(X_norm));
m = size(X,1);
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));

mu = mean(X);
sigma = std(X);
disp('mu'),disp(mu);
disp('sigma'),disp(sigma);

for i=1:m;
    X_norm(i,:) = (X(i,:)-mu )./ sigma;
end;
%disp('X_norm'),disp(X_norm);

2. 为X在最前面加上一列,构成最后需要使用的X,然后初始化alpha = 0.01; num_iters = 400;theta = zeros(3, 1);
[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);

function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)
%GRADIENTDESCENTMULTI Performs gradient descent to learn theta
%   theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by
%   taking num_iters gradient steps with learning rate alpha

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);

for iter = 1:num_iters
    h= zeros(m,1);
    disp('computeCostMulti');
    J_history(iter) = computeCostMulti(X, y, theta);%只是为了展示J的变化,计算实际的值时可以不需要
    
    h=X*theta; %计算hypothesis function
    tmp1 = zeros(size(X,2),1);
    for i=1:m
       tmp1= tmp1+(h(i)-y(i)).*X(i,:)'; %计算sum((hi-yi)*xi)
    end;
    theta = theta - (alpha/m)*tmp1;%计算Jtheta
    disp(J_history(iter));
    disp(theta);
end;


3. computeCostMulti计算函数如下:

function J = computeCostMulti(X, y, theta)
%COMPUTECOSTMULTI Compute cost for linear regression with multiple variables
%   J = COMPUTECOSTMULTI(X, y, theta) computes the cost of using theta as the
%   parameter for linear regression to fit the data points in X and y

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;

h= zeros(m,1);
h = X*theta;
J = (1/(2*m))*sum((h-y).^2);
disp('J'),disp(J);

方法二、采用正态等式,Normal Equation

function [theta] = normalEqn(X, y)
%NORMALEQN Computes the closed-form solution to linear regression 
%   NORMALEQN(X,y) computes the closed-form solution to linear 
%   regression using the normal equations.

theta = zeros(size(X, 2), 1);

theta = pinv(X'*X)*X'*y;

最后的主文件如下

%% Machine Learning Online Class
%  Exercise 1: Linear regression with multiple variables
%% Initialization
%% ================ Part 1: Feature Normalization ================

%% Clear and Close Figures
clear ; close all; clc

fprintf('Loading data ...\n');

%% Load Data
data = load('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);

% Print out some data points
fprintf('First 10 examples from the dataset: \n');
fprintf(' x = [%.0f %.0f], y = %.0f \n', [X(1:10,:) y(1:10,:)]');


% Scale features and set them to zero mean
fprintf('Normalizing Features ...\n');

[X mu sigma] = featureNormalize(X);

% Add intercept term to X
X = [ones(m, 1) X];


%% ================ Part 2: Gradient Descent ================

fprintf('Running gradient descent ...\n');

% Choose some alpha value
alpha = 0.01;
num_iters = 400;

% Init Theta and Run Gradient Descent 
theta = zeros(3, 1);
[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);

% Plot the convergence graph
figure;
plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);
xlabel('Number of iterations');
ylabel('Cost J');

% Display gradient descent's result
fprintf('Theta computed from gradient descent: \n');
fprintf(' %f \n', theta);
fprintf('\n');

% Estimate the price of a 1650 sq-ft, 3 br house
price = 0; % You should change this
X_p=[1650 3];
X_p = (X_p - mu)./sigma;
X_p = [1 X_p];
price = theta'*X_p';


% ============================================================

fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...
         '(using gradient descent):\n $%f\n'], price);

%% ================ Part 3: Normal Equations ================

fprintf('Solving with normal equations...\n');

%% Load Data
data = csvread('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);

% Add intercept term to X
X = [ones(m, 1) X];

% Calculate the parameters from the normal equation
theta = normalEqn(X, y);

% Display normal equation's result
fprintf('Theta computed from the normal equations: \n');
fprintf(' %f \n', theta);
fprintf('\n');


% Estimate the price of a 1650 sq-ft, 3 br house
price = 0; % You should change this
X_p=[1650 3];
X_p = [1 X_p];
disp(X_p');
price = theta'*X_p';

% ============================================================

fprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...
         '(using normal equations):\n $%f\n'], price);


网盘链接地址:http://pan.baidu.com/s/1sj0leqh

http://pan.baidu.com/s/1eQemQiA


你可能感兴趣的:(机器学习)