generated from LufsX/Experiment-LogReg
This commit is contained in:
+69
-48
@@ -27,78 +27,99 @@ name = "章程鸿"
|
|||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
from sklearn.preprocessing import StandardScaler
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
from sklearn.model_selection import train_test_split
|
||||||
|
|
||||||
def sigmoid(z):
|
def sigmoid(z):
|
||||||
return 1.0 / (1 + np.exp(-z))
|
"""Sigmoid 激活函数。"""
|
||||||
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
def compute_gradient(X_batch, y_batch, weights):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01, batch_size=32):
|
||||||
z = np.dot(X_batch, weights)
|
"""逻辑回归训练函数,随机初始化权重,并在每次迭代前打乱数据。"""
|
||||||
h = sigmoid(z)
|
|
||||||
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
|
|
||||||
return gradient
|
|
||||||
|
|
||||||
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64):
|
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
weights = np.random.randn(n) * 0.01
|
weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值
|
||||||
best_weights = weights.copy()
|
|
||||||
best_accuracy = 0
|
|
||||||
|
|
||||||
for _ in range(iterations):
|
for i in range(iterations):
|
||||||
|
# 每次迭代打乱数据
|
||||||
indices = np.random.permutation(m)
|
indices = np.random.permutation(m)
|
||||||
X_shuffled = X[indices]
|
X = X[indices]
|
||||||
y_shuffled = y[indices]
|
y = y[indices]
|
||||||
|
|
||||||
for j in range(0, m, batch_size):
|
for j in range(0, m, batch_size): # 按照 batch size 迭代
|
||||||
X_batch = X_shuffled[j:j + batch_size]
|
X_batch = X[j:j + batch_size]
|
||||||
y_batch = y_shuffled[j:j + batch_size]
|
y_batch = y[j:j + batch_size]
|
||||||
gradient = compute_gradient(X_batch, y_batch, weights)
|
|
||||||
|
z = np.dot(X_batch, weights)
|
||||||
|
predictions = sigmoid(z)
|
||||||
|
gradient = np.dot(X_batch.T, (predictions - y_batch)) / X_batch.shape[0]
|
||||||
|
|
||||||
|
# L2正则化
|
||||||
|
gradient += (lambda_reg / m) * weights
|
||||||
|
|
||||||
|
# 更新权重
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
# 计算训练集准确率
|
# 动态调整学习率,逐渐减小
|
||||||
train_accuracy = accuracy(X, y, weights)
|
learning_rate *= 0.99
|
||||||
if train_accuracy > best_accuracy:
|
|
||||||
best_accuracy = train_accuracy
|
|
||||||
best_weights = weights.copy()
|
|
||||||
|
|
||||||
return best_weights
|
return weights
|
||||||
|
|
||||||
def predict_logreg(X, weights):
|
def predict_logreg(inX, weights):
|
||||||
z = np.dot(X, weights)
|
"""逻辑回归预测函数。"""
|
||||||
h = sigmoid(z)
|
z = np.dot(inX, weights)
|
||||||
return np.where(h >= 0.5, 1, 0)
|
prediction_prob = sigmoid(z)
|
||||||
|
return 1 if prediction_prob >= 0.5 else 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()
|
values = line.strip().replace('?', '0').split()
|
||||||
if len(line) >= 1 and line[-1].isdigit():
|
try:
|
||||||
line_data = [0 if x == '?' else float(x) for x in line[:-1]]
|
values = [float(v) for v in values]
|
||||||
data.append(line_data)
|
|
||||||
labels.append(int(line[-1]))
|
# 合并特征23的取值
|
||||||
|
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
|
||||||
|
labels.append(0) # 死亡
|
||||||
|
elif values[22] == 1:
|
||||||
|
labels.append(1) # 生存
|
||||||
|
else:
|
||||||
|
continue # 无效标签,丢弃
|
||||||
|
|
||||||
|
# 用0填充缺失值
|
||||||
|
values = [0 if v == 0 else v for v in values] # 直接用0填充
|
||||||
|
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
data = np.array(data)
|
data = np.array(data)
|
||||||
labels = np.array(labels)
|
labels = np.array(labels)
|
||||||
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
|
|
||||||
|
|
||||||
return data, target_variable
|
return data, labels
|
||||||
|
|
||||||
def accuracy(X, y, weights):
|
def preprocess_data(X):
|
||||||
predictions = predict_logreg(X, weights)
|
"""特征标准化。"""
|
||||||
return np.mean(predictions == y)
|
scaler = StandardScaler()
|
||||||
|
return scaler.fit_transform(X)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X_train, y_train = load_data("./horse-colic.data")
|
# 加载数据集
|
||||||
X_test, y_test = load_data("./horse-colic.test")
|
X, y = load_data("./data/horse-colic.data")
|
||||||
|
|
||||||
# 标准化数据
|
# 归一化数据
|
||||||
scaler = StandardScaler()
|
X = preprocess_data(X)
|
||||||
X_train = scaler.fit_transform(X_train)
|
|
||||||
X_test = scaler.transform(X_test)
|
|
||||||
|
|
||||||
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64)
|
# 使用 train_test_split 打乱并随机抽取数据
|
||||||
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
||||||
|
|
||||||
final_accuracy = accuracy(X_test, y_test, final_weights)
|
# 训练逻辑回归模型,设置 batch size
|
||||||
print(f"最终测试集的准确率: {final_accuracy:.4f}")
|
batch_size = 32
|
||||||
|
weights = train_logreg(X_train, y_train, learning_rate=0.1, iterations=1000, lambda_reg=0.01, batch_size=batch_size)
|
||||||
|
|
||||||
|
# 测试单个数据
|
||||||
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
|
|||||||
Reference in New Issue
Block a user