Files
Experiment-LogReg/function.py
T
cy 1185899960
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 10s
更新 function.py
2024-10-26 17:39:23 +08:00

116 lines
3.2 KiB
Python

# function.py
import numpy as np
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 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
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423117"
name = "程悦"
def sigmoid(z):
return 1.0 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n)
for i in range(iterations):
z = np.dot(X, weights)
h = sigmoid(z)
gradient = np.dot(X.T, (h - y)) / m
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
h = sigmoid(z)
return 1 if h > 0.5 else 0
def load_data(filepath):
"""
从文件中加载数据,填充缺失值,并进行特征处理。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = []
labels = []
with open(filepath, 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip().split()
if len(line) >= 1 and line[-1].isdigit():
# 将缺失值 '?' 填充为 0,并转换为浮点数
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
data.append(line_data)
labels.append(int(line[-1]))
data = np.array(data)
labels = np.array(labels)
# 选择特征,合并目标变量
target_variable = labels
target_variable[(target_variable == 2) | (target_variable == 3)] = 0 # 合并死亡和安乐死为0
# 去掉特征3和特征24~28
data = np.delete(data, [2] + list(range(23, 28)), axis=1) # 特征3的索引是2,特征24-28的索引是23-27
scaler = StandardScaler()
data = scaler.fit_transform(data)
return data, target_variable
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")