更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 34s

This commit is contained in:
cy
2024-11-02 14:51:05 +08:00
parent 468a939c7a
commit 99dc5eaa7f
+65 -57
View File
@@ -1,8 +1,7 @@
# function.py # function.py
import numpy as np import numpy as np
from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import StandardScaler
from itertools import product from sklearn.model_selection import train_test_split, KFold
from sklearn.ensemble import RandomForestClassifier
""" """
实验说明: 实验说明:
@@ -27,92 +26,101 @@ id = "202210423117"
name = "程悦" name = "程悦"
def sigmoid(z): def sigmoid(z):
return 1.0 / (1 + np.exp(-z)) """Sigmoid 激活函数。"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=32):
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64, patience=100, decay_rate=0.95): """逻辑回归训练函数,随机初始化权重,并在每次迭代前打乱数据。"""
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
wait = 0
decay_step = iterations // 10 # 每10%的迭代衰减一次学习率
for i in range(iterations): for i in range(iterations):
# 每次迭代打乱数据
indices = np.random.permutation(m) indices = np.random.permutation(m)
X_shuffled = X[indices] X_shuffled = X[indices]
y_shuffled = y[indices] y_shuffled = 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_shuffled[j:j + batch_size]
y_batch = y_shuffled[j:j + batch_size] y_batch = y_shuffled[j:j + batch_size]
z = np.dot(X_batch, weights) z = np.dot(X_batch, weights)
h = sigmoid(z) predictions = sigmoid(z)
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch) 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) if i % 100 == 0:
print(f"Iteration {i + 1}, Train Accuracy: {train_accuracy:.4f}") learning_rate *= 0.95
if train_accuracy > best_accuracy:
best_accuracy = train_accuracy
best_weights = weights.copy()
wait = 0
else:
wait += 1
if i % decay_step == 0 and i > 0:
learning_rate *= decay_rate
print(f"Learning rate decayed to: {learning_rate:.6f}")
if wait >= patience:
print("Early stopping!")
break
return best_weights
return weights
def predict_logreg(X, weights): def predict_logreg(X, weights):
"""逻辑回归预测函数。"""
z = np.dot(X, weights) z = np.dot(X, weights)
h = sigmoid(z) prediction_prob = sigmoid(z)
return np.where(h > 0.5, 1, 0) return np.where(prediction_prob >= 0.5, 1, 0)
def load_data(filepath): def load_data(filepath):
data = [] data, labels = [], []
labels = []
with open(filepath, 'r') as f: with open(filepath, 'r') as f:
for line in f: for line in f.readlines():
parts = line.strip().split() line = line.strip().split()
if len(parts) >= 2 and parts[-1].isdigit(): if len(line) >= 1 and line[-1].isdigit():
line_data = [0 if x == '?' else float(x) for x in parts[:-1]] line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
label = int(parts[-1])
# 将标签映射到0和1(假设原始标签是1, 2, 3,我们将其映射为0和1)
target_label = 0 if label in [2, 3] else 1
data.append(line_data) data.append(line_data)
labels.append(target_label) labels.append(int(line[-1]))
data = np.array(data) data = np.array(data)
labels = np.array(labels) labels = np.array(labels)
return data, labels
target_variable = labels
target_variable[(target_variable == 2) | (target_variable == 3)] = 0
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
scaler = StandardScaler()
data = scaler.fit_transform(data)
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_train, y_train = load_data("./horse-colic.data") # 加载数据集
X_test, y_test = load_data("./horse-colic.test") X, y = load_data("./horse-colic.data")
# 标准化数据 # 使用 train_test_split 打乱并随机抽取数据
scaler = StandardScaler() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
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, patience=200) # K折交叉验证
k = 5
kf = KFold(n_splits=k, shuffle=True, random_state=42)
accuracies = []
final_accuracy = accuracy(X_test, y_test, final_weights) for train_index, val_index in kf.split(X_train):
print(f"最终测试集的准确率: {final_accuracy:.4f}") X_train_kf, X_val_kf = X_train[train_index], X_train[val_index]
y_train_kf, y_val_kf = y_train[train_index], y_train[val_index]
# 训练逻辑回归模型,设置 batch size
weights = train_logreg(X_train_kf, y_train_kf, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=32)
# 验证模型
val_accuracy = accuracy(X_val_kf, y_val_kf, weights)
accuracies.append(val_accuracy)
# 输出交叉验证的准确率和平均准确率
print(f"K折交叉验证得分: {accuracies}")
print(f"平均准确率: {np.mean(accuracies):.4f}")
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")