更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 12s

This commit is contained in:
2024-10-31 23:17:38 +08:00
parent 1c4de7c1c5
commit 54fc61c30c
+9 -13
View File
@@ -72,19 +72,15 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
# 初始化权重
weights = np.zeros(X.shape[1])
# 定义损失函数
def loss(w):
predictions = sigmoid(np.dot(X, w))
return -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))
for _ in range(iterations):
# 计算预测值
predictions = sigmoid(np.dot(X, weights))
# 计算梯度
gradient = np.dot(X.T, (predictions - y)) / len(y)
# 更新权重
weights -= learning_rate * gradient
# 定义梯度函数
def gradient(w):
predictions = sigmoid(np.dot(X, w))
return np.dot(X.T, (predictions - y)) / len(y)
# 使用minimize函数优化
result = minimize(loss, weights, method='BFGS', jac=gradient)
return result.x
return weights
def predict_logreg(inX, weights):
"""
@@ -113,4 +109,4 @@ if __name__ == "__main__":
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}") # 确保y_test[11]是整数
print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}")