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

This commit is contained in:
2024-11-01 21:07:21 +08:00
parent e9d8b95d6c
commit 372a05443a
+24 -9
View File
@@ -29,12 +29,17 @@ name = "章程鸿"
import numpy as np
from sklearn.preprocessing import StandardScaler
def sigmoid(z):
return 1.0 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=32, regularization_strength=0.1):
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64):
m, n = X.shape
weights = np.random.randn(n) * 0.01
best_weights = weights.copy()
best_accuracy = 0
wait = 0
for i in range(iterations):
indices = np.random.permutation(m)
@@ -44,18 +49,28 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000, batch_size=32, regul
for j in range(0, m, batch_size):
X_batch = X_shuffled[j:j + batch_size]
y_batch = y_shuffled[j:j + batch_size]
z = np.dot(X_batch, weights)
h = sigmoid(z)
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch) + regularization_strength * weights
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
weights -= learning_rate * gradient
return weights
# 计算训练集准确率
train_accuracy = accuracy(X, y, weights)
if train_accuracy > best_accuracy:
best_accuracy = train_accuracy
best_weights = weights.copy()
wait = 0
else:
wait += 1
return best_weights
def predict_logreg(X, weights):
z = np.dot(X, weights)
h = sigmoid(z)
return np.where(h >= 0.5, 1, 0)
return np.where(h > 0.5, 1, 0)
def load_data(filepath):
data = []
@@ -70,16 +85,18 @@ def load_data(filepath):
data = np.array(data)
labels = np.array(labels)
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
return data, target_variable
def accuracy(X, y, weights):
predictions = predict_logreg(X, weights)
return np.mean(predictions == y)
if __name__ == "__main__":
# 读取数据
X_train, y_train = load_data("./horse-colic.data")
X_test, y_test = load_data("./horse-colic.test")
@@ -88,9 +105,7 @@ if __name__ == "__main__":
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=5000, batch_size=64)
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64)
# 评估模型
final_accuracy = accuracy(X_test, y_test, final_weights)
print(f"最终测试集的准确率: {final_accuracy:.4f}")