generated from LufsX/Experiment-LogReg
This commit is contained in:
+41
-64
@@ -31,111 +31,88 @@ name = "严锡好"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
# Sigmoid函数,用于逻辑回归模型
|
||||
def sigmoid(z):
|
||||
return 1.0 / (1 + np.exp(-z))
|
||||
|
||||
# 计算梯度,用于逻辑回归的梯度下降算法
|
||||
def compute_gradient(X_batch, y_batch, weights, lambda_reg):
|
||||
z = np.dot(X_batch, weights) # 计算z值
|
||||
h = sigmoid(z) # 计算sigmoid函数值
|
||||
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch) # 计算梯度
|
||||
gradient += (lambda_reg / len(y_batch)) * weights # 添加L2正则化项
|
||||
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
|
||||
return gradient
|
||||
|
||||
# 训练逻辑回归模型
|
||||
# Adam优化器更新函数
|
||||
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
|
||||
v = beta2 * v + (1 - beta2) * (grad ** 2)
|
||||
m_hat = m / (1 - beta1 ** t)
|
||||
v_hat = v / (1 - beta2 ** t)
|
||||
return lr * m_hat / (np.sqrt(v_hat) + epsilon), m, v
|
||||
|
||||
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 # 存储最佳准确率
|
||||
m, n = X.shape
|
||||
weights = np.random.randn(n) * np.sqrt(2. / n)
|
||||
m_t, v_t = np.zeros(n), np.zeros(n)
|
||||
best_weights = weights.copy()
|
||||
best_accuracy = 0
|
||||
|
||||
for _ in range(iterations): # 迭代指定次数
|
||||
indices = np.random.permutation(m) # 随机打乱数据
|
||||
X_shuffled = X[indices] # 打乱特征
|
||||
y_shuffled = y[indices] # 打乱标签
|
||||
for epoch in range(iterations):
|
||||
indices = np.random.permutation(m)
|
||||
X_shuffled, y_shuffled = X[indices], y[indices]
|
||||
|
||||
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 # 更新权重
|
||||
for j in range(0, m, 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)
|
||||
update, m_t, v_t = adam_update(grad, m_t, v_t, epoch + 1, learning_rate)
|
||||
weights -= update
|
||||
|
||||
# 计算训练集准确率
|
||||
train_accuracy = accuracy(X, y, weights)
|
||||
if train_accuracy > best_accuracy: # 如果当前准确率更高,则更新最佳权重和准确率
|
||||
if train_accuracy > best_accuracy:
|
||||
best_accuracy = train_accuracy
|
||||
best_weights = weights.copy()
|
||||
|
||||
# 动态调整学习率
|
||||
if _ % 100 == 0 and train_accuracy > 0.95: # 每100次迭代检查一次,如果准确率超过0.95,则减小学习率
|
||||
if epoch % 100 == 0 and train_accuracy > 0.95:
|
||||
learning_rate *= 0.9
|
||||
|
||||
return best_weights
|
||||
|
||||
# 预测函数,用于逻辑回归模型
|
||||
def predict_logreg(X, weights):
|
||||
z = np.dot(X, weights) # 计算z值
|
||||
h = sigmoid(z) # 计算sigmoid函数值
|
||||
return np.where(h >= 0.5, 1, 0) # 返回预测结果
|
||||
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]] # 将非数字替换为0并转换为浮点数
|
||||
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])) # 将标签转换为整数
|
||||
labels.append(int(line[-1]))
|
||||
|
||||
data = np.array(data) # 转换为numpy数组
|
||||
labels = np.array(labels)
|
||||
|
||||
# 检查特征数量并进行特征选择
|
||||
num_features = data.shape[1]
|
||||
indices_to_delete = [2] # 特征3
|
||||
if num_features > 24: # 确保特征数量足够
|
||||
indices_to_delete += list(range(24, 27)) # 特征24到27
|
||||
|
||||
# 删除特征
|
||||
data, labels = np.array(data), np.array(labels)
|
||||
indices_to_delete = [2] + (list(range(24, 27)) if data.shape[1] > 24 else [])
|
||||
data = np.delete(data, indices_to_delete, axis=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) # 计算准确率
|
||||
predictions = predict_logreg(X, weights)
|
||||
return np.mean(predictions == y)
|
||||
|
||||
# 主函数
|
||||
if __name__ == "__main__":
|
||||
# 加载数据
|
||||
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)
|
||||
X_train, X_val = scaler.fit_transform(X_train), 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)
|
||||
|
||||
# 测试模型
|
||||
final_test_accuracy = accuracy(X_test, y_test, final_weights)
|
||||
print(f"最终测试集的准确率: {final_test_accuracy:.4f}")
|
||||
Reference in New Issue
Block a user