吳恩達機器學習第四周測驗及編程作業

代碼:https://github.com/LiuZhe6/AndrewNGMachineLearning

測驗:Neural Networks: Representation

第一題

在這裏插入圖片描述
答案
AD
分析:
B:錯誤,XOR需要三層。
C:輸出結果並不是概率,不一定和爲1。

第二題

在這裏插入圖片描述
答案
A
分析:畫出真值表

x1 x2 真值
0 0 1
0 1 1
1 0 1
1 1 0

第三題

在這裏插入圖片描述
答案
A

第四題

在這裏插入圖片描述
在這裏插入圖片描述
答案
A
分析:
x爲3 x 1的列向量,theta1爲3 x 3 的矩陣,故做乘法時爲 theta1 * x,並且sigmoid()不會改變乘法結果的大小,即a^(2)爲3*1列向量,符合神經網絡的定義。

第五題

在這裏插入圖片描述
答案
A
分析:交換了Layer2的兩個節點,同時將theta1兩行交換,並將theta2最後兩列交換,相當於對應參數都沒有發生變換,故值不變。


編程作業:

作業一:Regularized Logistic Regression

注意點:
注意CostFunction計算時,後部的theta平方里面theta(0)是不參與的,故在程序中theta(1)是不參與的。
注意gradient descent時,grad(0)是不正則化的!

lrCostFunction.m

% theta(0)不參與
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));
temp = theta;
temp(1) = 0;
grad = grad + lambda/m * temp; 

作業二:One-vs-All Classifier Training

oneVsAll.m

initial_theta = zeros(n + 1, 1);
options = optimset('GradObj', 'on', 'MaxIter', 50);

for c = 1:num_labels
    all_theta(c,:) =  fmincg(@(t)(lrCostFunction(t,X,(y==c),lambda)),initial_theta,options);
end

作業三:One-vs-All Classifier Prediction

predictOneVsAll.m

% 羅輯迴歸預測結果
A = sigmoid( X * all_theta') ;
% 獲得每一行最大值與下標
[x,index] = max (A,[],2);
% 將下標置給p,代表預測結果
p = index;

作業四:Neural Network Prediction Function

使用已經訓練好的Theta1 和 Theta2,直接可以通過神經網絡計算得到假設函數的結果,找到最大概率對應的下標,即爲預測手寫圖片對應的數字。

% a1加一列,值全爲1
a1 = [ones(m,1) X];

z2 = a1 * Theta1';

% 計算a2
a2 = sigmoid(z2);

% a2添加一列,值全爲1
a2 = [ones(size(z2,1),1) a2];

z3 = a2 * Theta2';

% 計算a3 
a3 = sigmoid(z3);


[value ,index] = max(a3, [] , 2);

p = index;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章