我是第一次测试机器学习。我只使用梯度下降和成本函数。我有两个变量。我希望能够在估算 x 值时预测 ay 值。但现在,我无法让梯度下降接近零。我弄乱了 alpha 和初始的 theta 值,我无法到达任何地方,我觉得我把它编程错了。这是我的代码:
x = [ 7, 8, 3, 2, 12, 1, 5]
y = [500000, 600000, 100000, 75000, 1000000, 5000, 200000]
let m = x.length
const alpha = 0.0001
let iterations = 1000
var theta0 = 0
var theta1 = 0
var hypothesis = x => theta0 + theta1* x;
function sumPre(){
sum = 0
for (let i = 0; i < m; i++) {
sum += hypothesis(x[i]) - y[i];
}
return sum
}
function sumPre2(){
sum = 0
for (let i = 0; i < m; i++) {
sum += (hypothesis(x[i]) - y[i]) * x[i];
}
return sum
}
function gD(){
let m = y.length;
var theta0 = 0
var theta1 = 0
for (let i = 0; i < iterations; i++) {
var thetaZero = theta0 - alpha * (1 / m) * sumPre();
var thetaOne = theta1 - alpha* (1 / m) * sumPre2();
var theta0 = thetaZero;
var theta1 = thetaOne;}
return [theta0,theta1]
}
var thetaZero = gD()[0];
var thetaOne = gD()[1]
console.log(thetaZero)
console.log(thetaOne)
var hypothesis = x => thetaZero + thetaOne* x;
//cost function
function cost(){
let sum = 0;
for (let i = 0; i < m; i++) {
sum += Math.pow(hypothesis(x[i]) - y[i], 2);
}
return sum / ( 2 * m)
}
console.log(cost())