【发布时间】:2020-05-24 16:58:03
【问题描述】:
我正在尝试使用 softmax 回归解决multiclass classification 问题(包含 3 个标签)。
这是我第一个使用梯度下降和反向传播(不使用正则化和任何高级优化算法)的粗略实现,仅包含 1 层。
此外,当学习率很大 (>0.003) 时,成本变为NaN,在降低学习率时,成本函数可以正常工作。
谁能解释我做错了什么??
# X is (13,177) dimensional
# y is (3,177) dimensional with label 0/1
m = X.shape[1] # 177
W = np.random.randn(3,X.shape[0])*0.01 # (3,13)
b = 0
cost = 0
alpha = 0.0001 # seems too small to me but for bigger values cost becomes NaN
for i in range(100):
Z = np.dot(W,X) + b
t = np.exp(Z)
add = np.sum(t,axis=0)
A = t/add
loss = -np.multiply(y,np.log(A))
cost += np.sum(loss)/m
print('cost after iteration',i+1,'is',cost)
dZ = A-y
dW = np.dot(dZ,X.T)/m
db = np.sum(dZ)/m
W = W - alpha*dW
b = b - alpha*db
这就是我得到的:
cost after iteration 1 is 6.661713420377916
cost after iteration 2 is 23.58974203186562
cost after iteration 3 is 52.75811642877174
.............................................................
...............*upto 100 iterations*.................
.............................................................
cost after iteration 99 is 1413.555298639879
cost after iteration 100 is 1429.6533630169406
【问题讨论】:
-
因为你在做
cost += np.sum(loss)/m应该是cost = np.sum(loss)/m
标签: machine-learning deep-learning gradient-descent backpropagation softmax