generated from LufsX/Experiment-LogReg
This commit is contained in:
+67
-97
@@ -1,8 +1,5 @@
|
|||||||
# function.py
|
import os
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
|
||||||
from sklearn.preprocessing import StandardScaler
|
|
||||||
from sklearn.model_selection import train_test_split, KFold
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
实验说明:
|
实验说明:
|
||||||
@@ -24,111 +21,84 @@ from sklearn.model_selection import train_test_split, KFold
|
|||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
id = "202210423209"
|
id = "202210218225"
|
||||||
name = "万子玉"
|
name = "周水源"
|
||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
|
import numpy as np
|
||||||
|
from sklearn.metrics import accuracy_score
|
||||||
|
|
||||||
|
# 定义sigmoid函数
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1.0 / (1 + np.exp(-z))
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
def compute_gradient(X_batch, y_batch, weights, lambda_reg):
|
# 训练逻辑回归模型
|
||||||
z = np.dot(X_batch, weights)
|
def train_logreg(X, y, learning_rate, iterations=1000):
|
||||||
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
|
|
||||||
|
|
||||||
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) # He初始化
|
weights = np.zeros(n)
|
||||||
best_weights = weights.copy()
|
bias = 0
|
||||||
best_accuracy = 0
|
|
||||||
|
|
||||||
for _ in range(iterations):
|
for _ in range(iterations):
|
||||||
indices = np.random.permutation(m)
|
z = np.dot(X, weights) + bias
|
||||||
X_shuffled = X[indices]
|
|
||||||
y_shuffled = 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
|
|
||||||
|
|
||||||
# 计算训练集准确率
|
|
||||||
train_accuracy = accuracy(X, y, weights)
|
|
||||||
if train_accuracy > best_accuracy:
|
|
||||||
best_accuracy = train_accuracy
|
|
||||||
best_weights = weights.copy()
|
|
||||||
|
|
||||||
# 动态调整学习率
|
|
||||||
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)
|
h = sigmoid(z)
|
||||||
return np.where(h >= 0.5, 1, 0)
|
dw = (1/m) * np.dot(X.T, (h - y))
|
||||||
|
db = (1/m) * np.sum(h - y)
|
||||||
|
weights -= learning_rate * dw
|
||||||
|
bias -= learning_rate * db
|
||||||
|
return weights, bias
|
||||||
|
|
||||||
|
# 使用逻辑回归模型进行预测
|
||||||
|
def predict_logreg(inX, weights, bias):
|
||||||
|
z = np.dot(inX, weights) + bias
|
||||||
|
h = sigmoid(z)
|
||||||
|
return 1 if h >= 0.5 else 0
|
||||||
|
|
||||||
|
# 加载数据
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
data, labels = [], []
|
data = []
|
||||||
with open(filepath, 'r') as f:
|
with open(filepath, 'r') as file:
|
||||||
for line in f:
|
for line in file:
|
||||||
line = line.strip().split()
|
cleaned_line = line.strip().replace('?', '0')
|
||||||
if len(line) >= 1 and line[-1].isdigit():
|
values = [float(x) for x in cleaned_line.split()]
|
||||||
line_data = [0 if x == '?' else float(x) for x in line[:-1]]
|
if values[22] in [2, 3]:
|
||||||
data.append(line_data)
|
values[22] = 0
|
||||||
labels.append(int(line[-1]))
|
new_values = values[:2] + values[3:23]
|
||||||
|
data.append(new_values)
|
||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
labels = np.array(labels)
|
X = data[:, :-1]
|
||||||
|
y = data[:, -1]
|
||||||
|
return X, y
|
||||||
|
|
||||||
# 检查特征数量
|
# 寻找最佳学习率
|
||||||
num_features = data.shape[1]
|
def find_best_learning_rate(X, y, learning_rates, iterations=1000):
|
||||||
|
best_accuracy = 0
|
||||||
|
best_learning_rate = None
|
||||||
|
best_weights = None
|
||||||
|
best_bias = None
|
||||||
|
for rate in learning_rates:
|
||||||
|
weights, bias = train_logreg(X, y, rate, iterations)
|
||||||
|
y_pred = np.array([predict_logreg(x, weights, bias) for x in X])
|
||||||
|
accuracy = accuracy_score(y, y_pred)
|
||||||
|
if accuracy > best_accuracy:
|
||||||
|
best_accuracy = accuracy
|
||||||
|
best_learning_rate = rate
|
||||||
|
best_weights = weights
|
||||||
|
best_bias = bias
|
||||||
|
return best_learning_rate, best_accuracy, best_weights, best_bias
|
||||||
|
|
||||||
# 特征选择:去掉特征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__":
|
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, y_test = load_data("./data/horse-colic.test")
|
||||||
X_test = scaler.transform(X_test)
|
|
||||||
|
|
||||||
# 测试模型
|
# 定义要尝试的学习率列表
|
||||||
final_test_accuracy = accuracy(X_test, y_test, final_weights)
|
learning_rates = np.linspace(0.001, 0.1, 50)
|
||||||
print(f"最终测试集的准确率: {final_test_accuracy:.4f}")
|
|
||||||
|
# 寻找最佳学习率
|
||||||
|
best_learning_rate, best_accuracy, best_weights, best_bias = find_best_learning_rate(X_train, y_train, learning_rates)
|
||||||
|
|
||||||
|
print(f"最佳学习率: {best_learning_rate}")
|
||||||
|
print(f"最佳准确率: {best_accuracy}")
|
||||||
|
|
||||||
|
# 使用最佳权重和偏置进行预测
|
||||||
|
y_pred = predict_logreg(X_test[11], best_weights, best_bias)
|
||||||
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
Reference in New Issue
Block a user