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

This commit is contained in:
cy
2024-11-01 21:19:10 +08:00
parent 7ae904507c
commit a9b39382ba
+32 -76
View File
@@ -31,19 +31,12 @@ def sigmoid(z):
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):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
Returns:
- numpy array: 训练得到的权重。
"""
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)
@@ -57,99 +50,62 @@ def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64, regul
h = sigmoid(z)
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 * weights / len(y_batch)
weights -= learning_rate * gradient
# 学习率衰减
# 计算训练集准确率
train_accuracy = accuracy(X, y, weights)
if train_accuracy > best_accuracy:
best_accuracy = train_accuracy
best_weights = weights.copy()
wait = 0
else:
wait += 1
if i % 100 == 0:
learning_rate *= 0.95
return weights
return best_weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
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 np.where(h > 0.5, 1, 0)
def load_data(filepath):
"""
从文件中加载数据,填充缺失值,并进行特征处理。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data, labels = [], []
data = []
labels = []
with open(filepath, 'r') as f:
for line in f:
line = line.strip().split()
if line and line[-1].isdigit():
line_data = [1] + [0 if x == '?' else float(x) for x in line[:-1]]
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)
# 映射标签
labels[np.isin(labels, [2, 3])] = 0
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
# 删除不需要的列
data = np.delete(data, [2] + list(range(23, 28)), axis=1)
return data, target_variable
# 数据标准化
scaler = StandardScaler()
data = scaler.fit_transform(data)
return data, labels
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")
X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
# 使用随机森林进行初步预测
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
# 标准化数据
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
rf_predictions_train = rf_model.predict(X_train)
rf_predictions_test = rf_model.predict(X_test)
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64)
# 将随机森林预测的结果作为新的特征
X_train_combined = np.column_stack((X_train, rf_predictions_train))
X_test_combined = np.column_stack((X_test, rf_predictions_test))
# 使用逻辑回归进行训练
final_weights = train_logreg(X_train_combined, y_train, learning_rate=0.01,
iterations=5000, batch_size=32,
regularization='L1', lambda_reg=0.01)
# 计算准确率
final_accuracy = accuracy(X_test_combined, y_test, final_weights)
final_accuracy = accuracy(X_test, y_test, final_weights)
print(f"最终测试集的准确率: {final_accuracy:.4f}")