当我运行代码时,它会交替生成0或1的theta。 就像是 首次运行代码:仅预测0 第二次运行代码:仅预测1
class logistic_regression():
def H(self, X, theta):
z = np.dot( X, theta)
return 1 / (1 + np.exp(-z))
def cost_function(self, X, theta, y):
h = self.H(X , theta)
return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
def gradient_descent(self, X, y, theta, iters, alpha):
self.cost = np.zeros(iters)
h = self.H(X , theta)
gradient = np.dot( X.T, ( h - y )) / y.shape[0]
for i in range(iters):
theta -= alpha * gradient
self.cost[i] = self.cost_function(X, theta, y)
return theta, cost
def predictions(self, X, theta, threshold=0.5):
return self.H(X, theta) >= threshold
#applying the code
lr = logistic_regression()
new_theta, cost = lr.gradient_descent(X, y, theta, iters, alpha)
result = lr.H(X, new_theta)
print(new_theta)
print('\n')
print(result)
#output 1st time
[ -2.6197013 -8.62233216 -107.01170844]
[0. 0. 0. ... 0. 0. 0.]
#output 2nd time
[ 8.55507128 139.32508563 129.80393891]
[1. 1. 1. ... 1. 1. 1.]
没有错误消息,但无法正常工作