일전에 누가 학교 과제 못했다고 징징거린 기억이 나서, 마침 오늘 시간 나서 찾아봄. 이런거지
m = numel(y);
%% 1. Build Thetas
Thetas = nnThetaCell(nn_params, [input_layer_size hidden_layer_size_vector num_labels]);
%% 2. Set y_matrix
y_matrix = eye(num_labels)(y,:); % permutation over identity matrix of size num_labels!
%% 3. Init configuration
activationLayers = {[ones(m, 1) X]};
Zs = {};
sum_Thetas = 0;
num_theta = numel(Thetas);
num_layers = num_theta + 1;
%% 3. forward propagation
for thetai = 1:num_theta
z = activationLayers{thetai} * Thetas{thetai}';
if num_theta > thetai
activationLayers{thetai + 1} = [ones(m,1) sigmoid(z)];
else
activationLayers{thetai + 1} = sigmoid(z);
end
sum_Thetas = sum_Thetas + sum(sum(Thetas{thetai}(:,2:end) .^ 2));
Zs{thetai + 1} = z;
end
%% 4. backpropagation
error_d = activationLayers{num_layers} - y_matrix;
Deltas = {};
for i = num_layers-1:-1:1
Delta = error_d' * activationLayers{i};
Deltas{i} = Delta;
if i > 1 % Don't process input layer
error_d = error_d * Thetas{i}(:, 2:end) .* sigmoidGradient(Zs{i});
end
end
%% 5. compute J
true_classification = y_matrix .* log(activationLayers{num_layers});
false_classification = (1 - y_matrix) .* log(1 - activationLayers{num_layers});
scaled_sum_Thetas = (lambda * sum_Thetas)/ (2 * m);
J = -1/m * sum(sum(true_classification + false_classification)) + ...
scaled_sum_Thetas;
%% 6. Compute grad
grad = [];
for i = 1:num_theta
Thetas{i}(:, 1) = 0;
Theta_grad = 1/m * (Deltas{i} + lambda * Thetas{i});
grad = [grad; Theta_grad(:)];
end
사실 오래 전에 프갤에 올라 왔던 글인데 프갤만 잘 뒤져봐도 나왔을텐데 ㅋ
변수 이름 짓기만 잘해도 대충 이해가 되는 부분이고, 일단 벡터화 가능한 고급언어로 정답 버전을 만들어서 쓰고, 필요에 따라 저급언어로 포팅하는 거를 권장ㅇㅇ
근데, 실전에서는 나라면 R 시스템을 서버로 두고 앱서버가 젖절한 입력갑 해당 서버로 보내서 결과만 받을 듯. 이미 구현된 라이브러리 쓰지 내가 구현은 안함 ㅇㅇ
명심하자. 실전에서는 니가 직접 알고리듬 구현하는 것 보다는 제대로 된 데이터를 주고 받는 검증 시스템 및 관리 시스템이 더 중요하게 된다