Я написал некоторый код для нерегулярной функции стоимости логистической регрессии и для нахождения градиента, но независимо от того, что я пытаюсь, мой код продолжает возвращать ту же ошибку TypeError.
Я уже пробовал векторизацию иРеализация цикла для моего кода и ничего не работает. Я также хотел бы отметить, что грейдер всегда оценивает мою функцию стоимости с полными оценками, но не кодом для поиска частных производных. Мои результаты всегда соответствуют ожидаемой стоимости, но ничего не возвращается для градиентной части.
В нем говорится, что это стоимость: J (?) = 1?∑? = 1? [−? (?) log (ℎ?)(? (?))) - (1 − ? (?)) log (1 − ℎ? (? (?)))]
И это частная производная: ∂? (?) ∂?? =1?∑? = 1? (ℎ? (? (?)) - ? (?)) ? (?) ?
(Из курса я могу убедиться, что это правильно)
def costFunction(theta, X, y):
# Initialize some useful values
m = y.size # number of training examples
# You need to return the following variables correctly
J = 0
grad = np.zeros(theta.shape)
# ====================== YOUR CODE HERE ============
for i in range(m):
hypothesis = sigmoid(np.dot(theta.T, X[i, :]))
J += y[i] * math.log(hypothesis) + (1 - y[i]) * math.log(1 - hypothesis)
for j in range(n):
grad = (hypothesis - y[i]) * X[i, j]
J = (-1 / m) * J
grad = (1 / m) * grad
# =============================================================
return J, grad
# Initialize fitting parameters
initial_theta = np.zeros(n+1)
cost, grad = costFunction(initial_theta, X, y)
print('Cost at initial theta (zeros): {:.3f}'.format(cost))
print('Expected cost (approx): 0.693\n')
print('Gradient at initial theta (zeros):')
#print('\t[{:.4f}, {:.4f}, {:.4f}]'.format(*grad))
print('Expected gradients (approx):\n\t[-0.1000, -12.0092, -11.2628]\n')
# Compute and display cost and gradient with non-zero theta
test_theta = np.array([-24, 0.2, 0.2])
cost, grad = costFunction(test_theta, X, y)
print('Cost at test theta: {:.3f}'.format(*cost))
print('Expected cost (approx): 0.218\n')
print('Gradient at test theta:')
print('\t[{:.3f}, {:.3f}, {:.3f}]'.format(*grad))
print('Expected gradients (approx):\n\t[0.043, 2.566, 2.647]')
Я ожидаю, что результат будет:
Cost at initial theta (zeros): 0.693
Expected cost (approx): 0.693
Gradient at initial theta (zeros):
[-0.1000, -12.0092, -11.2628]
Expected gradients (approx):
[-0.1000, -12.0092, -11.2628]
, но вместо этого я получаю следующее:
Cost at initial theta (zeros): 0.693
Expected cost (approx): 0.693
Gradient at initial theta (zeros):
Expected gradients (approx):
[-0.1000, -12.0092, -11.2628]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-ab2a7b541269> in <module>()
15 cost, grad = costFunction(test_theta, X, y)
16
---> 17 print('Cost at test theta: {:.3f}'.format(*cost))
18 print('Expected cost (approx): 0.218\n')
19
TypeError: format() argument after * must be an iterable, not numpy.float64