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

This commit is contained in:
2024-11-02 16:17:07 +08:00
parent daa62cdcd5
commit c1c3aa2a5f
+38 -23
View File
@@ -29,34 +29,50 @@ name = "章程鸿"
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
def load_data(filepath):
data, labels = [], []
with open(filepath, 'r') as f:
for line in f:
line = line.strip().split()
if len(line) >= 1 and line[-1].isdigit():
line_data = [0 if x == '?' else float(x) for x in line[:-1]]
data.append(line_data)
labels.append(int(line[-1]))
data = np.array(data)
labels = np.array(labels)
def sigmoid(z):
return 1.0 / (1 + np.exp(-z))
# 检查特征数量
num_features = data.shape[1]
def compute_gradient(X_batch, y_batch, weights, lambda_reg):
z = np.dot(X_batch, weights)
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
# 特征选择:去掉特征3(索引2)和特征24~28(索引23~26),确保索引有效
indices_to_delete = [2] # 特征3
if num_features > 24: # 确保特征数量足够
indices_to_delete += list(range(24, 27)) # 特征24到27(索引23到26)
def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
m, n = X.shape
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化
best_weights = weights.copy()
best_accuracy = 0
# 删除特征
data = np.delete(data, indices_to_delete, axis=1)
for _ in range(iterations):
indices = np.random.permutation(m)
X_shuffled = X[indices]
y_shuffled = y[indices]
# 将标签二分类化,特征23(索引22)取值2和3合并为0,其余为1
target_variable = np.where((labels == 2) | (labels == 3), 0, 1)
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
return data, target_variable
# 计算训练集准确率
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)
return np.where(h >= 0.5, 1, 0)
def load_data(filepath):
data, labels = [], []
@@ -73,7 +89,6 @@ def load_data(filepath):
# 检查特征数量
num_features = data.shape[1]
print(f"特征数量: {num_features}")
# 特征选择:去掉特征3(索引2)和特征24~28(索引23~26),确保索引有效
indices_to_delete = [2] # 特征3