문제 설명
이 for 루프에서 fminunc가 매번 동일한 결과를 제공하는 이유는 무엇입니까? (Why is fminunc in this for loop giving the same result each time?)
for 루프에서 'fminunc'를 여러 번 실행하려고 합니다.
코드의 일부:
6P = 0.70 ;
idx = randperm(m);
X_Training = X(idx(1:round(P*m)),:);
X_Testing = X(idx(round(P*m)+1:end),:);
y_Traning = y(idx(1:round(P*m)),:);
y_Testing = y(idx(round(P*m)+1:end),:);
s = 100;
border_all = zeros( 2, s );
lambda = 1;
accuracy = 0;
initial_theta = zeros( n + 1, 1 );
options = optimset( 'GradObj', 'on', 'MaxIter', 400 );
for i = 1 : 1 : s
[theta, J, exit_flag] = fminunc( @(t) costFunctionReg( t, X_Training, y_Traning, lambda ), initial_theta, options );
for border = 0.01 : 0.01 : 1
p = predict( theta, X_Testing, border );
accuracy_t = mean( double( p == y_Testing ) ) * 100;
if accuracy_t > accuracy
accuracy = accuracy_t;
border_result = border;
endif
endfor
border_all(1, i) = border_result;
border_all(2, i) = accuracy;
endfor
나중에 "theta"의 출력 값을 사용하여 다른 변경 사항을 확인합니다. 변수 "i"(i=1:1:s..의 경우). 스크립트를 실행할 때마다 "ta"가 계산되지만 다른 "for 루프" 반복에서는 변경되지 않습니다. 그러나 모든 반복에서 약간씩 달라야 합니다.
동시에 스크립트를 다시 실행하면 "theta"라는 새로운 값을 얻습니다. 따라서 첫 번째 반복에서만 처음부터 계산되고 다른 반복에서는 계산되지 않는 것 같습니다. 아마도 메모리 문제가 있을 수 있습니다. 'clear' 기능을 시도했지만 결과는 동일합니다.
같은 문제에 직면한 사람이 있습니까?
참조 솔루션
방법 1:
Converting comment thread to an answer for anyone googling with a similar problem:
This is because once you enter the for loop, the inputs to
fminunc
never change again, so you are effectively always calling it with the same inputs, and therefore getting the same output out.Move the randomized initializations at the top part of your code snippet inside the for loop, and you will get different outputs each time, as you intend.
(by Ula、Tasos Papastylianou)