generated from LufsX/Experiment-LogReg
This commit is contained in:
+9
-13
@@ -72,19 +72,15 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|||||||
# 初始化权重
|
# 初始化权重
|
||||||
weights = np.zeros(X.shape[1])
|
weights = np.zeros(X.shape[1])
|
||||||
|
|
||||||
# 定义损失函数
|
for _ in range(iterations):
|
||||||
def loss(w):
|
# 计算预测值
|
||||||
predictions = sigmoid(np.dot(X, w))
|
predictions = sigmoid(np.dot(X, weights))
|
||||||
return -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions))
|
# 计算梯度
|
||||||
|
gradient = np.dot(X.T, (predictions - y)) / len(y)
|
||||||
|
# 更新权重
|
||||||
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
# 定义梯度函数
|
return weights
|
||||||
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
|
|
||||||
|
|
||||||
def predict_logreg(inX, weights):
|
def predict_logreg(inX, weights):
|
||||||
"""
|
"""
|
||||||
@@ -113,4 +109,4 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
# 测试单个数据
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test[11], weights)
|
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])}")
|
||||||
Reference in New Issue
Block a user