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

This commit is contained in:
cy
2024-11-02 21:41:15 +08:00
parent a6c9249c53
commit a50cfb03af
+55 -36
View File
@@ -24,67 +24,78 @@ from sklearn.model_selection import KFold
id = "202210423117"
name = "程悦"
def sigmoid(z):
"""计算Sigmoid激活函数值"""
return 1.0 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.05,
iterations=1500,
batch_size=64, regularization='L2', lambda_reg=0.05, cv=5):
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64,
regularization='L2', lambda_reg=0.05, cv=5):
"""训练逻辑回归模型并使用交叉验证计算权重"""
m, n = X.shape
kf = KFold(n_splits=cv, shuffle=True)
weights_list = []
fold_scores = []
for train_index, val_index in kf.split(X):
X_train, X_val = X[train_index], X[val_index]
y_train, y_val = y[train_index], y[val_index]
weights = np.random.randn(n) * 0.01
for i in range(iterations):
for _ in range(iterations):
indices = np.random.permutation(len(X_train))
X_shuffled = X_train[indices]
y_shuffled = y_train[indices]
X_shuffled, y_shuffled = X_train[indices], y_train[indices]
for j in range(0, len(X_train), 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)) / X_batch.shape[0]
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch)
# 正则化处理
if regularization == 'L1':
gradient += lambda_reg * np.sign(weights) / len(y_batch)
elif regularization == 'L2':
gradient += (lambda_reg / m) * weights
gradient += (lambda_reg / len(y_train)) * weights
weights -= learning_rate * gradient
if i % 100 == 0:
learning_rate *= 0.95
# 在验证集上计算准确率
predictions = [predict_logreg(x, weights) for x in X_val]
if _ % 100 == 0:
learning_rate *= 0.95 # 动态调整学习率
# 验证集准确率
predictions = predict_logreg(X_val, weights)
score = np.mean(predictions == y_val)
fold_scores.append(score)
weights_list.append(weights)
# 对权重进行加权平均融合,权重为各折的准确率
# 权重加权平均
total_score = sum(fold_scores)
if total_score == 0:
return weights_list[-1]
averaged_weights = np.zeros(n)
for weight, score in zip(weights_list, fold_scores):
averaged_weights += weight * score
averaged_weights /= total_score
return averaged_weights
return averaged_weights / total_score
def predict_logreg(inX, weights):
z = np.dot(inX, weights)
def predict_logreg(X, weights):
"""对输入数据进行逻辑回归预测"""
z = np.dot(X, weights)
h = sigmoid(z)
return 1 if h > 0.5 else 0
return (h > 0.5).astype(int)
def load_data(filepath):
"""加载数据并处理缺失值"""
data, labels = [], []
with open(filepath, 'r') as f:
for line in f.readlines():
for line in f:
line = line.strip().split()
if len(line) >= 1 and line[-1].isdigit():
if line and line[-1].isdigit():
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
data.append(line_data)
labels.append(int(line[-1]))
@@ -92,39 +103,47 @@ def load_data(filepath):
data = np.array(data)
labels = np.array(labels)
target_variable = labels
target_variable[(target_variable == 2) | (target_variable == 3)] = 0
# 处理目标变量
labels[(labels == 2) | (labels == 3)] = 0
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
# 数据标准化
scaler = StandardScaler()
data = scaler.fit_transform(data)
return data, target_variable
return data, labels
def accuracy(X, y, weights):
predictions = [predict_logreg(x, weights) for x in X]
"""计算模型的准确率"""
predictions = predict_logreg(X, weights)
return np.mean(predictions == y)
def ensemble_predict(X, models):
predictions = [predict_logreg(x, model) for model in models for x in X]
ensemble_predictions = [1 if np.sum(pred == 1) > len(models) / 2 else 0 for pred in np.array(predictions).reshape(-1, len(models))]
return ensemble_predictions
def ensemble_predict(X, models, weights):
"""集成模型预测"""
predictions = np.array([predict_logreg(X, model) for model in models]) # (num_models, num_samples)
weighted_predictions = np.tensordot(predictions, weights, axes=(0, 0)) # 权重加权
return (weighted_predictions > 0.5).astype(int) # 返回最终预测
if __name__ == "__main__":
X_train, y_train = load_data("./horse-colic.data")
X_test, y_test = load_data("./horse-colic.test")
X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
# 训练多个模型
num_models = 5
models = [train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, batch_size=32, regularization='None',
lambda_reg=0.01) for _ in range(num_models)]
models = [train_logreg(X_train, y_train, learning_rate=0.02, iterations=6000,
batch_size=48, regularization='None', lambda_reg=0.02)
for _ in range(num_models)]
# 模型准确率作为权重
model_accuracies = [accuracy(X_train, y_train, model) for model in models]
weights = np.array(model_accuracies) / sum(model_accuracies)
# 集成预测
ensemble_predictions = ensemble_predict(X_test, models)
ensemble_predictions = ensemble_predict(X_test, models, weights)
final_accuracy = np.mean(ensemble_predictions == y_test)
print(f"最终测试集的准确率: {final_accuracy:.4f}")
print(f"最终测试集的准确率: {final_accuracy:.4f}")