Coursera-AndrewNg(吳恩達)機器學習筆記——第四周編程作業(多分類與神經網絡)


多分類問題——識別手寫體數字0-9

一.邏輯回歸解決多分類問題

1.圖片像素為20*20,X的屬性數目為400,輸出層神經元個數為10,分別代表1-10(把0映射為10)。

通過以下代碼先形式化展示數據 ex3data1.mat內容:

load('ex3data1.mat'); % training data stored in arrays X, y
m = size(X, 1); %求出樣本總數
% Randomly select 100 data points to display
rand_indices = randperm(m); %函數功能隨機打亂這m個數字,輸出給rand_indices.
sel = X(rand_indices(1:100), :); %按照打亂后的數列取出100個數字,作為X矩陣的行數。

displayData(sel); %通過本函數將選出的X矩陣中100個樣本進行圖形化

函數displayData()實現解析如下:

function [h, display_array] = displayData(X, example_width)
%DISPLAYDATA Display 2D data in a nice grid

if ~exist('example_width', 'var') || isempty(example_width) 
    example_width = round(sqrt(size(X, 2)));   %四舍五入求出圖片的寬度
end

colormap(gray); %將圖片定義為灰色系

[m n] = size(X);
example_height = (n / example_width); %求出圖片的高度

% Compute number of items to display
display_rows = floor(sqrt(m));  %計算出每行每列展示多少個數字圖片
display_cols = ceil(m / display_rows);

pad = 1; %圖片之間間隔

% Setup blank display 創建要展示的圖片像素大小,空像素,數字圖片之間有1像素間隔
display_array = - ones(pad + display_rows * (example_height + pad), ...
                       pad + display_cols * (example_width + pad));

% Copy each example into a patch on the display array  將像素點填充進去
curr_ex = 1;
for j = 1:display_rows
    for i = 1:display_cols
        if curr_ex > m, 
            break; 
        end% Get the max value of the patch
        max_val = max(abs(X(curr_ex, :)));
        display_array(pad + (j - 1) * (example_height + pad) + (1:example_height), ...
                      pad + (i - 1) * (example_width + pad) + (1:example_width)) = ...
                        reshape(X(curr_ex, :), example_height, example_width) / max_val; %reshape函數進行矩陣維數轉換
        curr_ex = curr_ex + 1;
    end
    if curr_ex > m, 
        break; 
    end
end

h = imagesc(display_array, [-1 1]); %將像素點畫為圖片
axis image off %不顯示坐標軸
drawnow; %刷新屏幕
end

 

2.向量化邏輯回歸

向量化代價函數和梯度下降,代碼同第三周編程練習相同:http://www.cnblogs.com/LoganGo/p/9009767.html

核心代碼如下:

function [J, grad] = lrCostFunction(theta, X, y, lambda)

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

J = 0;
grad = zeros(size(theta));
%分別計算代價值J和梯度grad J
=1/m*(-(y')*log(sigmoid(X*theta))-(1-y)'*log(1-sigmoid(X*theta)))+lambda/(2*m)*(theta'*theta-theta(1)^2); %grad = 1/m*X'*(sigmoid(X*theta)-y)+lambda*theta/m; %grad(1) = grad(1)-lambda*theta(1)/m; grad=1/m*X'*(sigmoid(X*theta)-y)+lambda/m*([0;theta(2:end)]); grad = grad(:);

end

 

3.邏輯回歸解決多分類問題

oneVsAll.m函數解析:通過閱讀原文中所給的英文解析,足夠完成本函數的編寫

function [all_theta] = oneVsAll(X, y, num_labels, lambda)

m = size(X, 1);
n = size(X, 2);

all_theta = zeros(num_labels, n + 1); %為訓練1-10個便簽,所以需要矩陣為10*n+1

X = [ones(m, 1) X];
%運用了fmincg()函數求參數,與函數fminunc()相比,處理屬性過多時更高效!
options = optimset('GradObj', 'on', 'MaxIter', 50); 
for c=1:num_labels,
  all_theta(c,:)=fmincg(@(t)(lrCostFunction(t, X, (y==c), lambda)), all_theta(c,:)', options)';
end
end

預測函數predictOneVsAll()函數編寫:

function p = predictOneVsAll(all_theta, X)

m = size(X, 1);
num_labels = size(all_theta, 1);

p = zeros(size(X, 1), 1);
X = [ones(m, 1) X];
index=0;
pre=zeros(num_labels,1); %存儲每個樣本對應數字1-10的預測值
for c=1:m, for d=1:num_labels, pre(d)=sigmoid(X(c,:)*(all_theta(d,:)')); end [maxnum index]=max(pre); p(c)=index; %找到該樣本最大的預測值所對應的數字,作為實際預測值 end end

 

二.神經網絡解決多分類問題

使用已經訓練好的參數θ1θ2來做預測,predict.m如下:

function p = predict(Theta1, Theta2, X)

m = size(X, 1);
num_labels = size(Theta2, 1);
X=[ones(m,1) X]; %為a1添加為1的偏置

p = zeros(size(X, 1), 1);

for i=1:m, %分別對m個樣本做預測
  a2=sigmoid(Theta1*X(i,:)'); %計算a2
  a2=[1;a2];                  %為a2添加為1的偏置
  a3=sigmoid(Theta2*a2);      %計算a3
  [manum index]=max(a3);      %求出哪個數字的預測值最大
  p(i)=index;                 %得出預測值
end
end

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM