generated from LufsX/Experiment-LogReg
This commit is contained in:
+68
-50
@@ -1,9 +1,10 @@
|
|||||||
# function.py
|
# function.py
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
from sklearn.model_selection import train_test_split, KFold
|
||||||
|
from sklearn.preprocessing import MinMaxScaler
|
||||||
from sklearn.impute import SimpleImputer
|
from sklearn.impute import SimpleImputer
|
||||||
from sklearn.preprocessing import StandardScaler
|
from sklearn.preprocessing import StandardScaler
|
||||||
from sklearn.model_selection import train_test_split
|
|
||||||
from sklearn.metrics import accuracy_score, classification_report
|
from sklearn.metrics import accuracy_score, classification_report
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@@ -31,88 +32,105 @@ name = "严锡好"
|
|||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
|
# Sigmoid函数,用于逻辑回归模型
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1.0 / (1 + np.exp(-z))
|
return 1.0 / (1 + np.exp(-z))
|
||||||
|
|
||||||
|
# 计算梯度,用于逻辑回归的梯度下降算法
|
||||||
def compute_gradient(X_batch, y_batch, weights, lambda_reg):
|
def compute_gradient(X_batch, y_batch, weights, lambda_reg):
|
||||||
z = np.dot(X_batch, weights)
|
z = np.dot(X_batch, weights) # 计算z值
|
||||||
h = sigmoid(z)
|
h = sigmoid(z) # 计算sigmoid函数值
|
||||||
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
|
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch) # 计算梯度
|
||||||
gradient += (lambda_reg / len(y_batch)) * weights
|
gradient += (lambda_reg / len(y_batch)) * weights # 添加L2正则化项
|
||||||
return gradient
|
return gradient
|
||||||
|
|
||||||
# Adam优化器更新函数
|
# Adam优化器更新函数
|
||||||
def adam_update(grad, m, v, t, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):
|
def adam_update(grad, m, v, t, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):
|
||||||
m = beta1 * m + (1 - beta1) * grad
|
m = beta1 * m + (1 - beta1) * grad # 更新一阶矩估计
|
||||||
v = beta2 * v + (1 - beta2) * (grad ** 2)
|
v = beta2 * v + (1 - beta2) * (grad ** 2) # 更新二阶矩估计
|
||||||
m_hat = m / (1 - beta1 ** t)
|
m_hat = m / (1 - beta1 ** t) # 计算偏差校正的一阶矩
|
||||||
v_hat = v / (1 - beta2 ** t)
|
v_hat = v / (1 - beta2 ** t) # 计算偏差校正的二阶矩
|
||||||
return lr * m_hat / (np.sqrt(v_hat) + epsilon), m, v
|
return lr * m_hat / (np.sqrt(v_hat) + epsilon), m, v # 返回更新步长和更新后的一阶矩和二阶矩
|
||||||
|
|
||||||
|
# 训练逻辑回归模型,使用Adam优化器
|
||||||
def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
|
def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
|
||||||
m, n = X.shape
|
m, n = X.shape # 获取样本数量和特征数量
|
||||||
weights = np.random.randn(n) * np.sqrt(2. / n)
|
weights = np.random.randn(n) * np.sqrt(2. / n) # 使用He初始化权重
|
||||||
m_t, v_t = np.zeros(n), np.zeros(n)
|
m_t, v_t = np.zeros(n), np.zeros(n) # 初始化Adam优化器的一阶矩和二阶矩
|
||||||
best_weights = weights.copy()
|
best_weights = weights.copy() # 存储最佳权重
|
||||||
best_accuracy = 0
|
best_accuracy = 0 # 存储最佳准确率
|
||||||
|
|
||||||
for epoch in range(iterations):
|
for epoch in range(iterations): # 迭代指定次数
|
||||||
indices = np.random.permutation(m)
|
indices = np.random.permutation(m) # 随机打乱数据
|
||||||
X_shuffled, y_shuffled = X[indices], y[indices]
|
X_shuffled, y_shuffled = X[indices], y[indices] # 打乱特征和标签
|
||||||
|
|
||||||
for j in range(0, m, batch_size):
|
for j in range(0, m, batch_size): # 按批次处理数据
|
||||||
X_batch, y_batch = X_shuffled[j:j + batch_size], y_shuffled[j:j + batch_size]
|
X_batch, y_batch = X_shuffled[j:j + batch_size], y_shuffled[j:j + batch_size] # 获取当前批次的特征和标签
|
||||||
grad = compute_gradient(X_batch, y_batch, weights, lambda_reg)
|
grad = compute_gradient(X_batch, y_batch, weights, lambda_reg) # 计算梯度
|
||||||
update, m_t, v_t = adam_update(grad, m_t, v_t, epoch + 1, learning_rate)
|
update, m_t, v_t = adam_update(grad, m_t, v_t, epoch + 1, learning_rate) # 使用Adam优化器更新权重
|
||||||
weights -= update
|
weights -= update # 更新权重
|
||||||
|
|
||||||
train_accuracy = accuracy(X, y, weights)
|
train_accuracy = accuracy(X, y, weights) # 计算训练集准确率
|
||||||
if train_accuracy > best_accuracy:
|
if train_accuracy > best_accuracy: # 如果当前准确率更高,则更新最佳权重和准确率
|
||||||
best_accuracy = train_accuracy
|
best_accuracy = train_accuracy
|
||||||
best_weights = weights.copy()
|
best_weights = weights.copy()
|
||||||
|
|
||||||
if epoch % 100 == 0 and train_accuracy > 0.95:
|
if epoch % 100 == 0 and train_accuracy > 0.95: # 每100次迭代检查一次,如果准确率超过0.95,则减小学习率
|
||||||
learning_rate *= 0.9
|
learning_rate *= 0.9
|
||||||
|
|
||||||
return best_weights
|
return best_weights
|
||||||
|
|
||||||
|
# 预测函数,用于逻辑回归模型
|
||||||
def predict_logreg(X, weights):
|
def predict_logreg(X, weights):
|
||||||
z = np.dot(X, weights)
|
z = np.dot(X, weights) # 计算z值
|
||||||
h = sigmoid(z)
|
h = sigmoid(z) # 计算sigmoid函数值
|
||||||
return np.where(h >= 0.5, 1, 0)
|
return np.where(h >= 0.5, 1, 0) # 返回预测结果
|
||||||
|
|
||||||
|
# 加载数据函数
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
data, labels = [], []
|
data, labels = [], []
|
||||||
with open(filepath, 'r') as f:
|
with open(filepath, 'r') as f: # 打开文件
|
||||||
for line in f:
|
for line in f: # 逐行读取
|
||||||
line = line.strip().split()
|
line = line.strip().split() # 去除空格并分割
|
||||||
if len(line) >= 1 and line[-1].isdigit():
|
if len(line) >= 1 and line[-1].isdigit(): # 确保行数据有效
|
||||||
line_data = [0 if x == '?' else float(x) for x in line[:-1]]
|
line_data = [0 if x == '?' else float(x) for x in line[:-1]] # 将非数字替换为0并转换为浮点数
|
||||||
data.append(line_data)
|
data.append(line_data)
|
||||||
labels.append(int(line[-1]))
|
labels.append(int(line[-1])) # 将标签转换为整数
|
||||||
|
|
||||||
data, labels = np.array(data), np.array(labels)
|
data, labels = np.array(data), np.array(labels) # 转换为numpy数组
|
||||||
indices_to_delete = [2] + (list(range(24, 27)) if data.shape[1] > 24 else [])
|
|
||||||
|
# 特征选择:去掉特征3(索引2)和特征24~28(索引23~26),确保索引有效
|
||||||
|
indices_to_delete = [2] # 特征3
|
||||||
|
if data.shape[1] > 24: # 确保特征数量足够
|
||||||
|
indices_to_delete += list(range(24, 27)) # 特征24到27(索引23到26)
|
||||||
|
|
||||||
|
# 删除特征
|
||||||
data = np.delete(data, indices_to_delete, axis=1)
|
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)
|
target_variable = np.where((labels == 2) | (labels == 3), 0, 1)
|
||||||
|
|
||||||
return data, target_variable
|
return data, target_variable
|
||||||
|
|
||||||
|
# 计算准确率函数
|
||||||
def accuracy(X, y, weights):
|
def accuracy(X, y, weights):
|
||||||
predictions = predict_logreg(X, weights)
|
predictions = predict_logreg(X, weights) # 预测结果
|
||||||
return np.mean(predictions == y)
|
return np.mean(predictions == y) # 计算准确率
|
||||||
|
|
||||||
|
# 主函数
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X, y = 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)
|
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42) # 拆分训练集和验证集
|
||||||
|
|
||||||
scaler = MinMaxScaler()
|
scaler = MinMaxScaler() # 初始化归一化对象
|
||||||
X_train, X_val = scaler.fit_transform(X_train), scaler.transform(X_val)
|
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)
|
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)
|
val_accuracy = accuracy(X_val, y_val, final_weights) # 验证模型
|
||||||
print(f"验证集的准确率: {val_accuracy:.4f}")
|
print(f"验证集的准确率: {val_accuracy:.4f}") # 打印验证集准确率
|
||||||
|
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test") # 加载测试集
|
||||||
X_test = scaler.transform(X_test)
|
X_test = scaler.transform(X_test) # 测试集归一化
|
||||||
final_test_accuracy = accuracy(X_test, y_test, final_weights)
|
final_test_accuracy = accuracy(X_test, y_test, final_weights) # 测试模型
|
||||||
print(f"最终测试集的准确率: {final_test_accuracy:.4f}")
|
print(f"最终测试集的准确率: {final_test_accuracy:.4f}") # 打印测试集准确率
|
||||||
Reference in New Issue
Block a user