【发布时间】:2018-03-31 21:05:28
【问题描述】:
目标:是使用scipy fmin_tnc优化器优化成本函数。
问题:虽然成本和梯度函数在单独执行时表现如预期,但当通过 fmin_tnc 优化时相同的初始参数 - 返回 zeros 数组。
见下面的代码:
def sigmoid(z_vec):
return 1/(1 + np.exp(-z_vec))
def hypothesis(X_vec, weights_vec):
_hypothesis = np.vectorize(sigmoid)
return _hypothesis(X_vec.dot(weights_vec.T))
def cost(X_vec, weight_vec, labels):
X_vec = np.matrix(X_vec)
labels = np.matrix(Y_labels)
weight_vec = np.matrix(weight_vec)
lhs = np.multiply(-1*labels, np.log(hypothesis(X_vec, weight_vec)))
rhs = np.multiply((1-labels), np.log(1 - hypothesis(X_vec, weight_vec)))
return np.sum(lhs - rhs)/labels.shape[0]
def gradient(X_vec, weight_vec, labels):
X_vec = np.matrix(X_vec)
labels = np.matrix(Y_labels)
weight_vec = np.matrix(weight_vec)
grad_result = np.zeros(weight_vec.shape[1])
error = hypothesis(X_vec, weight_vec) - labels
for i in range(weight_vec.shape[1]):
grad_result[i] = np.sum(np.multiply(error, X_vec[:,i])) / len(X_vec)
return grad_result
# optimize cost function
# asssume all train-set/labels and initial parameters are loaded correctly
result = opt.fmin_tnc(func=cost, x0=theta_weights, fprime=gradient, args=(X_examples, Y_labels))
输出
result[0] ===> [0, 0, 0] ===> 没有发生优化/学习。
我认为我有问题,但对我来说并不明显。任何正确的见解都会有所帮助。
【问题讨论】:
标签: python numpy optimization scipy logistic-regression