Files
experiment2.1/function.py
T
43606070 46c8d94622
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 11s
更新 function.py
2024-11-02 15:47:28 +08:00

104 lines
2.7 KiB
Python

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 = "202210423118"
name = "刘国庆"
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
# Load the data, treating missing values as NaN
try:
data = np.genfromtxt(filepath, delimiter=',', missing_values='?', filling_values=np.nan)
# Remove rows with NaN values
data = data[~np.isnan(data).any(axis=1)]
# Split into features and labels
X = data[:, :-1] # Features
y = data[:, -1] # Labels
return X, y
except Exception as e:
print(f"Error loading data: {e}")
return None, None
def sigmoid(z):
"""
Sigmoid activation function.
"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, epochs=1000):
"""
训练逻辑回归模型。
Args:
- X (np.array): 特征数据。
- y (np.array): 标签数据。
- learning_rate (float): 学习率。
- epochs (int): 训练的迭代次数。
Returns:
- np.array: 训练后的权重。
"""
# Initialize weights
X = np.c_[np.ones(X.shape[0]), X] # Add intercept term
weights = np.zeros(X.shape[1])
# Gradient descent for logistic regression
for epoch in range(epochs):
z = np.dot(X, weights)
predictions = sigmoid(z)
# Calculate the gradient
gradient = np.dot(X.T, (predictions - y)) / y.size
weights -= learning_rate * gradient
return weights
def predict_logreg(X, weights):
"""
使用逻辑回归模型进行预测。
Args:
- X (np.array): 特征数据。
- weights (np.array): 训练得到的权重。
Returns:
- np.array: 预测的标签(0 或 1)。
"""
X = np.c_[np.ones(X.shape[0]), X] # Add intercept term
probabilities = sigmoid(np.dot(X, weights))
return (probabilities >= 0.5).astype(int)