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

This commit is contained in:
2024-10-31 17:07:00 +08:00
parent eb1086b2d6
commit 8581c9a8ce
+38 -7
View File
@@ -1,6 +1,6 @@
# function.py
import numpy as np
from scipy.optimize import minimize
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
@@ -19,10 +19,10 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
202210423219李燕如
"""
id = "202210423xxx"
name = "test_name"
id = "202210423219"
name = "李燕如"
# 这里写自己的代码实现
@@ -30,15 +30,28 @@ def train_logreg(X, y, other_params="你自己设置一些其它参数"):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
Args: - X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
Returns:
- numpy array: 训练得到的权重。
"""
# 添加截距项
X = np.c_[np.ones(X.shape[0]), X]
# 初始化权重
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))
# 定义梯度函数
def gradient(w):
predictions = sigmoid(np.dot(X, w))
return np.dot(X.T, (predictions - y)) / len(y)
# 使用BFGS算法优化
result = fmin_bfgs(loss, weights, fprime=gradient, maxiter=iterations)
return result
def predict_logreg(inX, weights):
"""
@@ -51,6 +64,9 @@ def predict_logreg(inX, weights):
Returns:
- int: 预测的分类标签。
"""
inX = np.c_[1, inX] # 添加截距项
prob = sigmoid(np.dot(inX, weights))
return 1 if prob > 0.5 else 0
# 这里也写自己的代码实现
@@ -65,7 +81,21 @@ def load_data(filepath):
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.loadtxt(filepath, delimiter=',', skiprows=1)
X = data[:, :-1]
y = data[:, -1]
return X, y
def sigmoid(z):
"""
Sigmoid函数。
Args:
- z (numpy array): 输入值。
Returns:
- numpy array: Sigmoid函数的输出值。
"""
return 1 / (1 + np.exp(-z))
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
@@ -81,3 +111,4 @@ if __name__ == "__main__":
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")