Files
Experiment-LogReg/function.py
T
luderby 8346632a7b
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 12s
更新 function.py
2024-11-05 11:16:27 +08:00

110 lines
3.4 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
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "20221042323"
name = "李顺潮"
# 这里写自己的代码实现
def train_logreg(X, y, other_params=None):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n) # 初始化权重
learning_rate = 0.01 # 学习率设置
num_iterations = 1000 # 迭代次数
# 对率回归的梯度下降
for _ in range(num_iterations):
linear_model = np.dot(X, weights)
predictions = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
errors = y - predictions
weights += learning_rate * np.dot(X.T, errors) / m # 更新权重
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
linear_model = np.dot(inX, weights)
predictions = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
return np.round(predictions).astype(int) # 返回0或1
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,处理缺失值并确保格式正确。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
# 加载数据,使用适当的分隔符和设置
data = np.genfromtxt(filepath, delimiter=',', dtype=None, encoding=None, invalid_raise=False, filling_values=np.nan, autostrip=True)
print("Loaded data shape:", data.shape) # 打印数据的形状
# 检查是否成功加载了二维数据
if data.ndim == 1:
raise ValueError("Loaded data is one-dimensional, please check the file format.")
X = data[:, :-1].astype(float) # 假设最后一列为标签
y = data[:, -1] # 最后一列为标签
# 检查有效索引
valid_indices = ~np.isnan(X).any(axis=1) & ~np.isnan(y)
X = X[valid_indices]
y = y[valid_indices]
y = np.where(y == 1, 1, 0)
return X, y
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")