generated from LufsX/Experiment-LogReg
This commit is contained in:
+111
-92
@@ -1,115 +1,134 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.model_selection import train_test_split, KFold
|
||||
|
||||
# 这里填写学号和姓名
|
||||
id = "202210218225"
|
||||
name = "周水源"
|
||||
"""
|
||||
实验说明:
|
||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||
|
||||
注意事项:
|
||||
- 在 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 = "202210423209"
|
||||
name = "万子玉"
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def sigmoid(z):
|
||||
"""
|
||||
Sigmoid 函数,将输入值映射到 (0, 1) 的范围。
|
||||
"""
|
||||
return 1 / (1 + np.exp(-z))
|
||||
return 1.0 / (1 + np.exp(-z))
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.1):
|
||||
"""
|
||||
对率回归训练函数,加入了 L2 正则化。
|
||||
def compute_gradient(X_batch, y_batch, weights, lambda_reg):
|
||||
z = np.dot(X_batch, weights)
|
||||
h = sigmoid(z)
|
||||
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
|
||||
gradient += (lambda_reg / len(y_batch)) * weights # L2正则化
|
||||
return gradient
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- learning_rate (float): 学习率,默认值为 0.01。
|
||||
- iterations (int): 梯度下降迭代次数,默认值为 1000。
|
||||
- lambda_reg (float): 正则化强度,默认值为 0.1。
|
||||
def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
|
||||
m, n = X.shape
|
||||
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化
|
||||
best_weights = weights.copy()
|
||||
best_accuracy = 0
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
# 初始化权重
|
||||
weights = np.zeros(X.shape[1])
|
||||
|
||||
# 梯度下降
|
||||
for i in range(iterations):
|
||||
# 计算预测值
|
||||
predictions = sigmoid(np.dot(X, weights))
|
||||
|
||||
# 计算误差
|
||||
error = predictions - y
|
||||
|
||||
# 计算梯度,并加入正则化项
|
||||
gradient = np.dot(X.T, error) / len(y) + lambda_reg * weights / len(y)
|
||||
weights -= learning_rate * gradient
|
||||
|
||||
# 每 100 次迭代输出一次损失
|
||||
if i % 100 == 0:
|
||||
loss = -np.mean(y * np.log(predictions) + (1 - y) * np.log(1 - predictions)) + (lambda_reg / (2 * len(y))) * np.sum(weights**2)
|
||||
print(f"Iteration {i}, Loss: {loss:.4f}")
|
||||
|
||||
return weights
|
||||
for _ in range(iterations):
|
||||
indices = np.random.permutation(m)
|
||||
X_shuffled = X[indices]
|
||||
y_shuffled = y[indices]
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
for j in range(0, m, batch_size):
|
||||
X_batch = X_shuffled[j:j + batch_size]
|
||||
y_batch = y_shuffled[j:j + batch_size]
|
||||
gradient = compute_gradient(X_batch, y_batch, weights, lambda_reg)
|
||||
weights -= learning_rate * gradient
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
# 计算训练集准确率
|
||||
train_accuracy = accuracy(X, y, weights)
|
||||
if train_accuracy > best_accuracy:
|
||||
best_accuracy = train_accuracy
|
||||
best_weights = weights.copy()
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签 (0 或 1)。
|
||||
"""
|
||||
# 计算预测概率
|
||||
prob = sigmoid(np.dot(inX, weights))
|
||||
# 将概率转为标签
|
||||
return 1 if prob >= 0.5 else 0
|
||||
# 动态调整学习率
|
||||
if _ % 100 == 0 and train_accuracy > 0.95: # 达到高准确率时减小学习率
|
||||
learning_rate *= 0.9
|
||||
|
||||
return best_weights
|
||||
|
||||
def predict_logreg(X, weights):
|
||||
z = np.dot(X, weights)
|
||||
h = sigmoid(z)
|
||||
return np.where(h >= 0.5, 1, 0)
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,并处理 '?' 为每列的均值。
|
||||
"""
|
||||
data = []
|
||||
labels = []
|
||||
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
data, labels = [], []
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip().split()
|
||||
if not line:
|
||||
continue
|
||||
# 将特征转换为浮点型,处理 '?' 为 NaN
|
||||
features = [float(f) if f != '?' else np.nan for f in line[:-1]]
|
||||
label = int(line[-1])
|
||||
data.append(features)
|
||||
labels.append(label)
|
||||
|
||||
if len(line) >= 1 and line[-1].isdigit():
|
||||
line_data = [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)
|
||||
|
||||
# 计算每列的均值,并用均值替换 NaN
|
||||
col_means = np.nanmean(data, axis=0) # 计算每列的均值
|
||||
for i in range(data.shape[1]):
|
||||
data[:, i] = np.where(np.isnan(data[:, i]), col_means[i], data[:, i])
|
||||
|
||||
# 标准化数据(均值为 0,标准差为 1)
|
||||
means = np.mean(data, axis=0)
|
||||
stds = np.std(data, axis=0)
|
||||
data = (data - means) / stds
|
||||
# 检查特征数量
|
||||
num_features = data.shape[1]
|
||||
|
||||
return data, labels
|
||||
# 特征选择:去掉特征3和特征24~28,确保索引有效
|
||||
indices_to_delete = [2] # 特征3
|
||||
if num_features > 24: # 确保特征数量足够
|
||||
indices_to_delete += list(range(24, 27)) # 特征24到27
|
||||
|
||||
# 删除特征
|
||||
data = np.delete(data, indices_to_delete, axis=1)
|
||||
|
||||
# 将标签二分类化,特征23取值2和3合并为0,其余为1
|
||||
target_variable = np.where((labels == 2) | (labels == 3), 0, 1)
|
||||
|
||||
return data, target_variable
|
||||
|
||||
def accuracy(X, y, weights):
|
||||
predictions = predict_logreg(X, weights)
|
||||
return np.mean(predictions == y)
|
||||
|
||||
# 其余代码保持不变
|
||||
if __name__ == "__main__":
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
# 加载数据
|
||||
X, y = load_data("./data/horse-colic.data")
|
||||
|
||||
# 拆分训练集和验证集
|
||||
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
|
||||
|
||||
# 数据归一化
|
||||
scaler = MinMaxScaler()
|
||||
X_train = scaler.fit_transform(X_train)
|
||||
X_val = scaler.transform(X_val)
|
||||
|
||||
# 训练模型
|
||||
final_weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, batch_size=64, lambda_reg=0.1)
|
||||
|
||||
# 验证模型
|
||||
val_accuracy = accuracy(X_val, y_val, final_weights)
|
||||
print(f"验证集的准确率: {val_accuracy:.4f}")
|
||||
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
X_test = scaler.transform(X_test)
|
||||
|
||||
# 训练对率回归模型,加入正则化并增加迭代次数为 5000 次
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=10000, lambda_reg=0.01)
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
|
||||
# 测试整体准确率
|
||||
y_test_pred = np.array([predict_logreg(X_test[i], weights) for i in range(X_test.shape[0])])
|
||||
accuracy = np.mean(y_test_pred == y_test)
|
||||
print(f"测试集准确率: {accuracy:.4f}")
|
||||
# 测试模型
|
||||
final_test_accuracy = accuracy(X_test, y_test, final_weights)
|
||||
print(f"最终测试集的准确率: {final_test_accuracy:.4f}")
|
||||
Reference in New Issue
Block a user