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

This commit is contained in:
2024-11-07 16:37:17 +08:00
parent f98703e8c8
commit 4546a9a7bb
+47 -33
View File
@@ -1,46 +1,44 @@
# function.py
import numpy as np
# 这里填写学号和姓名
id = "202210218225"
name = "周水源"
def sigmoid(z):
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 function.py 中实现对率回归算法。
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。
测评环境:
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
- OS: Ubuntu 22.04.4 LTS
- Python: 3.10.12
- numpy: 2.1.1
Sigmoid 函数,将输入值映射到 (0, 1) 的范围。
"""
return 1 / (1 + np.exp(-z))
"""
请在这里填写学号和姓名,不填写即成绩无效。
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423xxx"
name = "test_name"
# 这里写自己的代码实现
def train_logreg(X, y, other_params="你自己设置一些其它参数"):
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
- learning_rate (float): 学习率,默认值为 0.01。
- iterations (int): 梯度下降迭代次数,默认值为 1000。
Returns:
- numpy array: 训练得到的权重。
"""
# 初始化权重
weights = np.zeros(X.shape[1])
# 梯度下降
for _ in range(iterations):
# 计算预测值
predictions = sigmoid(np.dot(X, weights))
# 计算误差
error = predictions - y
# 更新权重
gradient = np.dot(X.T, error) / len(y)
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
"""
@@ -51,26 +49,41 @@ def predict_logreg(inX, weights):
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
- int: 预测的分类标签 (0 或 1)。
"""
# 计算预测概率
prob = sigmoid(np.dot(inX, weights))
# 将概率转为标签
return 1 if prob >= 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
从文件中加载数据。
Args:
- directory (str): 数据文件路径。
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = []
labels = []
with open(filepath, 'r') as file:
for line in file:
line = line.strip().split()
if not line:
continue
# 将特征转换为浮点型
features = list(map(float, line[:-1]))
label = int(line[-1])
data.append(features)
labels.append(label)
return np.array(data), np.array(labels)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
@@ -83,3 +96,4 @@ if __name__ == "__main__":
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")