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

This commit is contained in:
2024-11-02 15:46:14 +08:00
parent 32ccf23d23
commit 275a84bc76
+55 -89
View File
@@ -26,40 +26,19 @@ name = "邓龙树"
# user_cod
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
def sigmoid(z):
"""Sigmoid 激活函数。"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, other_params=None):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (dict): 其它参数,可选设置。
Returns:
- numpy array: 训练得到的权重。
"""
if other_params is None:
other_params = {
'learning_rate': 0.1,
'iterations': 2000,
'lambda_reg': 0.01,
'batch_size': 32
}
learning_rate = other_params.get('learning_rate', 0.1)
iterations = other_params.get('iterations', 2000)
lambda_reg = other_params.get('lambda_reg', 0.01)
batch_size = other_params.get('batch_size', 32)
return 1.0 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.05, iterations=1500, batch_size=64, reg_lambda=0.01):
"""训练逻辑回归模型的函数,使用梯度下降算法。"""
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
for i in range(iterations):
indices = np.random.permutation(m)
@@ -69,86 +48,73 @@ def train_logreg(X, y, other_params=None):
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)
predictions = sigmoid(z)
gradient = np.dot(X_batch.T, (predictions - y_batch)) / X_batch.shape[0] + (lambda_reg / m) * weights
h = sigmoid(z)
gradient = np.dot(X_batch.T, (h - y_batch)) / len(y_batch) + reg_lambda * weights
weights -= learning_rate * gradient
if i % 100 == 0:
print(f"Iteration {i}, Learning Rate: {learning_rate}")
# 计算训练集准确率
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 weights
# 如果准确率没有提高,提前停止
if wait > 50:
break
def predict_logreg(inX, weights):
"""
对率回归预测函数。
return best_weights
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
prediction_prob = sigmoid(z)
return 1 if prediction_prob >= 0.5 else 0
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):
"""
从文件中加载数据。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
"""加载数据函数。"""
data = []
labels = []
with open(filepath, 'r') as f:
for line in f:
values = line.strip().replace('?', '0').split()
try:
values = [float(v) for v in values]
if values[22] == 2 or values[22] == 3:
labels.append(0)
data.append(values[:2] + values[3:23])
elif values[22] == 1:
labels.append(1)
data.append(values[:2] + values[3:23])
else:
continue
except ValueError:
continue
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)
target_variable = np.where((labels == 2) | (labels == 3), 0, labels)
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)
return np.mean(predictions == y)
if __name__ == "__main__":
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
X_train, y_train = load_data("./horse-colic.data")
X_test, y_test = load_data("./horse-colic.test")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 特征标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 训练对率回归模型
other_params = {
'learning_rate': 0.01,
'iterations': 1000,
'lambda_reg': 0.01,
'batch_size': 32
}
weights = train_logreg(X_train, y_train, other_params=other_params)
# 训练模型
final_weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=1500, batch_size=64, reg_lambda=0.01)
# 计算测试集准确率
final_accuracy = accuracy(X_test, y_test, final_weights)
print(f"最终测试集的准确率: {final_accuracy:.4f}")
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")