generated from LufsX/Experiment-LogReg
96 lines
2.7 KiB
Python
96 lines
2.7 KiB
Python
def load_data(filepath):
|
|
"""
|
|
从文件中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
|
|
|
|
Args:
|
|
- filepath (str): 数据文件路径。
|
|
|
|
id = "202210423118"
|
|
name = "刘国庆"
|
|
|
|
|
|
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.size == 0:
|
|
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
|
|
|
|
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)
|