generated from LufsX/Experiment-LogReg
This commit is contained in:
+93
-73
@@ -1,6 +1,3 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
"""
|
||||
实验说明:
|
||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||
@@ -19,92 +16,115 @@ import pandas as pd
|
||||
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
姓名请直接**填写中文**
|
||||
例如: name = "张三"
|
||||
"""
|
||||
id = "202210423115"
|
||||
name = "李煜锋"
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import MinMaxScaler
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
Args:
|
||||
- filepath (str): 数据文件路径。
|
||||
def sigmoid(z):
|
||||
return 1.0 / (1 + np.exp(-z))
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
# 使用空白作为分隔符读取数据
|
||||
data = pd.read_csv(filepath, sep='\s+', header=None, na_values='?')
|
||||
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
|
||||
|
||||
# 填充缺失值
|
||||
data.fillna(0, inplace=True)
|
||||
|
||||
# 处理目标变量,假设第 23 列是目标变量(索引 22)
|
||||
data[22] = data[22].replace({2: 0, 3: 0})
|
||||
|
||||
# 去掉特征 3(索引 2)及特征 24~28(索引 23~27),如果这些列存在
|
||||
columns_to_drop = [2, 23, 24, 25, 26, 27]
|
||||
data = data.drop(columns=[col for col in columns_to_drop if col in data.columns])
|
||||
|
||||
# 分离特征和标签
|
||||
X = data.drop(columns=[22]).to_numpy() # 特征数据
|
||||
y = data[22].to_numpy() # 标签数据
|
||||
return X, y
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- learning_rate (float): 学习率,默认值为0.01。
|
||||
- iterations (int): 迭代次数,默认值为1000。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
"""
|
||||
def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
|
||||
m, n = X.shape
|
||||
weights = np.zeros(n)
|
||||
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化
|
||||
best_weights = weights.copy()
|
||||
best_accuracy = 0
|
||||
|
||||
# 梯度下降法
|
||||
for _ in range(iterations):
|
||||
linear_model = np.dot(X, weights)
|
||||
predictions = 1 / (1 + np.exp(-linear_model)) # sigmoid函数
|
||||
# 更新权重
|
||||
weights += learning_rate * (1/m) * np.dot(X.T, (y - predictions))
|
||||
indices = np.random.permutation(m)
|
||||
X_shuffled = X[indices]
|
||||
y_shuffled = y[indices]
|
||||
|
||||
return 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
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
# 计算训练集准确率
|
||||
train_accuracy = accuracy(X, y, weights)
|
||||
if train_accuracy > best_accuracy:
|
||||
best_accuracy = train_accuracy
|
||||
best_weights = weights.copy()
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
# 动态调整学习率
|
||||
if _ % 100 == 0 and train_accuracy > 0.95: # 达到高准确率时减小学习率
|
||||
learning_rate *= 0.9
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
linear_model = np.dot(inX, weights)
|
||||
prediction = 1 / (1 + np.exp(-linear_model)) # sigmoid函数
|
||||
return 1 if prediction >= 0.5 else 0 # 采用0.5作为阈值
|
||||
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 f:
|
||||
for line in f:
|
||||
line = line.strip().split()
|
||||
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)
|
||||
|
||||
# 检查特征数量
|
||||
num_features = data.shape[1]
|
||||
|
||||
# 特征选择:去掉特征3(索引2)和特征24~28(索引23~26),确保索引有效
|
||||
indices_to_delete = [2] # 特征3
|
||||
if num_features > 24: # 确保特征数量足够
|
||||
indices_to_delete += list(range(24, 27)) # 特征24到27(索引23到26)
|
||||
|
||||
# 删除特征
|
||||
data = np.delete(data, indices_to_delete, axis=1)
|
||||
|
||||
# 将标签二分类化,特征23(索引22)取值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("./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("./horse-colic.test")
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
X_test = scaler.transform(X_test)
|
||||
|
||||
# 训练对率回归模型
|
||||
weights = train_logreg(X_train, y_train)
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
# 测试模型
|
||||
final_test_accuracy = accuracy(X_test, y_test, final_weights)
|
||||
print(f"最终测试集的准确率: {final_test_accuracy:.4f}")
|
||||
Reference in New Issue
Block a user