generated from LufsX/Experiment-LogReg
123 lines
3.8 KiB
Python
123 lines
3.8 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: 标签数据。
|
|
"""
|
|
for delimiter in [',', ' ', '\t']: # 尝试不同的分隔符:逗号、空格、制表符
|
|
try:
|
|
# Load data, filling missing values with NaN
|
|
data = np.genfromtxt(filepath, delimiter=delimiter, missing_values='?', filling_values=np.nan)
|
|
|
|
# Check if the data has been loaded correctly with at least two dimensions
|
|
if data.ndim < 2 or data.shape[1] < 2: # 至少需要两列:特征和标签
|
|
continue # 尝试下一个分隔符
|
|
|
|
# Remove rows with NaN values
|
|
data = data[~np.isnan(data).any(axis=1)]
|
|
|
|
# Ensure there's still data left after removing NaN
|
|
if data.size == 0:
|
|
print(f"Error: No valid data after removing NaN rows in file '{filepath}'.")
|
|
return None, None
|
|
|
|
# Split into features (X) and labels (y)
|
|
X = data[:, :-1] # Features
|
|
y = data[:, -1] # Labels
|
|
|
|
# Check if shapes of X and y match
|
|
if X.shape[0] != y.shape[0]:
|
|
print(f"Error: Feature and label count mismatch in file '{filepath}'")
|
|
return None, None
|
|
|
|
# 输出数据形状供检查
|
|
print(f"Loaded data from '{filepath}': {X.shape[0]} samples, {X.shape[1]} features.")
|
|
|
|
return X, y
|
|
except Exception as e:
|
|
print(f"Error loading data with delimiter '{delimiter}': {e}")
|
|
|
|
print(f"Error: File '{filepath}' may be empty or improperly formatted.")
|
|
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)
|
|
|