generated from LufsX/Experiment-LogReg
This commit is contained in:
+6
-10
@@ -1,10 +1,5 @@
|
||||
import numpy as np
|
||||
|
||||
"""
|
||||
实验说明:
|
||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||
"""
|
||||
|
||||
# 填写学号和姓名
|
||||
id = "202210423213" # 请替换为实际学号
|
||||
name = "熊浩燃" # 请替换为实际姓名
|
||||
@@ -42,19 +37,20 @@ def train_logreg(X, y, learning_rate=0.01, iterations=5000, reg_lambda=0.1):
|
||||
|
||||
return weights
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
def predict_logreg(inX, weights, threshold=0.3):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
对率回归预测函数,包含自定义阈值。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
- threshold (float): 分类阈值,默认为0.3。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
probability = sigmoid(np.dot(inX, weights))
|
||||
return 1 if probability >= 0.5 else 0
|
||||
return 1 if probability >= threshold else 0
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
@@ -88,6 +84,6 @@ if __name__ == "__main__":
|
||||
# 训练对率回归模型
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, reg_lambda=0.1)
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
# 使用自定义阈值测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights, threshold=0.3)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
|
||||
Reference in New Issue
Block a user