Я новичок в Matlab и Machine Learning, и я попытался выполнить функцию градиентного спуска без использования матрицы.Градиентный спуск с несколькими переменными без матрицы
- м это число, например, на моем обучающего множества
- п это число функции для каждого примера
Функция gradientDescentMulti принимает 5 аргументов:
- X mxn Матрица
- у м-мерный вектор
- тета: п-мерный вектор
- альфа: вещественное число
- nb_iters: действительное число
У меня уже есть раствор с использованием умножения матрицы
function theta = gradientDescentMulti(X, y, theta, alpha, num_iters)
for iter = 1:num_iters
gradJ = 1/m * (X'*X*theta - X'*y);
theta = theta - alpha * gradJ;
end
end
Результат после итераций:
theta =
1.0e+05 *
3.3430
1.0009
0.0367
Но теперь, я попытался сделать то же самое без умножения матриц, это функция:
function theta = gradientDescentMulti(X, y, theta, alpha, num_iters)
m = length(y); % number of training examples
n = size(X, 2); % number of features
for iter = 1:num_iters
new_theta = zeros(1, n);
%// for each feature, found the new theta
for t = 1:n
S = 0;
for example = 1:m
h = 0;
for example_feature = 1:n
h = h + (theta(example_feature) * X(example, example_feature));
end
S = S + ((h - y(example)) * X(example, n)); %// Sum each feature for this example
end
new_theta(t) = theta(t) - alpha * (1/m) * S; %// Calculate new theta for this example
end
%// only at the end of the function, update all theta simultaneously
theta = new_theta'; %// Transpose new_theta (horizontal vector) to theta (vertical vector)
end
end
В результате, вся тета являются то же:/
theta =
1.0e+04 *
3.5374
3.5374
3.5374