leetcode 困难题 内存100 1515. 服务中心的最佳位置 Best Position for a Service Centre - const double eps = 1e-22
Problem: leetcode 困难题 内存100 1515. 服务中心的最佳位置 Best Position for a Service Centre
用到了神经网络里面的梯度下降算法,也就是当前的人工智能里面的梯度下降方向传播算法
配置了learning_rate=0.01学XI率,配置了最大的epoch=1000000,训练的过程中记录了最小值mi,初始化service centre的坐标是x和y的average的(cx, cy)
前向传播公式:
loss
=
∑
(
x
i
−
c
x
)
2
+
(
y
i
−
c
y
)
2
2
\text{loss}=\sum\sqrt[2]{(x_i-cx)^2+(y_i-cy)^2}
loss=∑2(xi−cx)2+(yi−cy)2
反向传播求梯度的公式:
∂
loss
x
i
=
x
i
−
c
x
(
x
i
−
c
x
)
2
+
(
y
i
−
c
y
)
2
2
\frac{\partial\text{loss}}{x_i}=\frac{x_i-cx}{\sqrt[2]{(x_i-cx)^2+(y_i-cy)^2}}
xi∂loss=2(xi−cx)2+(yi−cy)2 拼多多帮助力入口
xi−cx,
∂
loss
y
i
=
y
i
−
c
y
(
x
i
−
c
x
)
2
+
(
y
i
−
c
y
)
2
2
\frac{\partial\text{loss}}{y_i}=\frac{y_i-cy}{\sqrt[2]{(x_i-cx)^2+(y_i-cy)^2}}
yi∂loss=2(xi−cx)2+(yi−cy)2
yi−cy
update(cx, cy)公式:
c
x
=
c
x
−
∂
loss
x
i
∗
l
r
cx=cx - \frac{\partial\text{loss}}{x_i}*lr
cx=cx−xi∂loss∗lr,
c
y
=
c
y
−
∂
loss
y
i
∗
l
r
cy=cy - \frac{\partial\text{loss}}{y_i}*lr
cy=cy−yi∂loss∗lr
这里的lr就是learning_rate=0.01学XI率
当到达了epoch时停止,或者目标target变化值 < gap也停止,最后返回最小值
因数据太少了,而且分布不均匀,导致了训练不收敛,最后不得不记录最小值mi,用来做返回值的
Code
class Solution {
public:
const long long epoch = 1000000;
long long cnt = 0;
const double eps = 1e-22;
const double gap = 1e-9;
double getMinDistSum(vector>& positions) {int x = 0, y = 0, n = positions.size();
if(n==1) return 0;
for(vector& tmp : positions) {
x += tmp[0];
y += tmp[1];
}
double learning_rate = 0.01, tx, ty, sum, mi = INT_MAX;
double cx = x / (double)n, cy = y / (double)n, pre = 1000.0;
while(cnt < epoch) {
double gradx = 0, grady = 0, power;
sum = 0;
for(vector& tmp : positions) {
tx = cx - (double)tmp[0];
ty = cy - (double)tmp[1];
power = sqrt(pow(tx, 2) + pow(ty, 2));
sum += power;
gradx += tx / (power + eps);
grady += ty / (power + eps);
}
cx = cx - gradx * learning_rate;
cy = cy - grady * learning_rate;
if(fabs(pre - sum) < gap) {
pre = sum;
break;
}
if(mi > sum) mi = sum;
pre = sum;
cnt++;
}
return mi;
}
};