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

This commit is contained in:
2024-11-02 14:54:23 +08:00
parent 32d6db105a
commit 4e3df65082
+70 -60
View File
@@ -34,45 +34,80 @@ def sigmoid(z):
"""Sigmoid 激活函数。""" """Sigmoid 激活函数。"""
return 1 / (1 + np.exp(-z)) return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=32): 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)
m, n = X.shape m, n = X.shape
weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值 weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值
for i in range(iterations): for i in range(iterations):
# 每次迭代打乱数据
indices = np.random.permutation(m) indices = np.random.permutation(m)
X = X[indices] X_shuffled = X[indices]
y = y[indices] y_shuffled = y[indices]
for j in range(0, m, batch_size): # 按照 batch size 迭代 for j in range(0, m, batch_size):
X_batch = X[j:j + batch_size] X_batch = X_shuffled[j:j + batch_size]
y_batch = y[j:j + batch_size] y_batch = y_shuffled[j:j + batch_size]
z = np.dot(X_batch, weights) z = np.dot(X_batch, weights)
predictions = sigmoid(z) predictions = sigmoid(z)
gradient = np.dot(X_batch.T, (predictions - y_batch)) / X_batch.shape[0] gradient = np.dot(X_batch.T, (predictions - y_batch)) / X_batch.shape[0] + (lambda_reg / m) * weights
# L2正则化
gradient += (lambda_reg / m) * weights
# 更新权重
weights -= learning_rate * gradient weights -= learning_rate * gradient
# 动态调整学习率,逐渐减小 if i % 100 == 0:
if i % 100 == 0: # 每100次迭代输出一次学习率
print(f"Iteration {i}, Learning Rate: {learning_rate}") print(f"Iteration {i}, Learning Rate: {learning_rate}")
return weights return weights
def predict_logreg(inX, weights): def predict_logreg(inX, weights):
"""逻辑回归预测函数。""" """
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights) z = np.dot(inX, weights)
prediction_prob = sigmoid(z) prediction_prob = sigmoid(z)
return 1 if prediction_prob >= 0.5 else 0 return 1 if prediction_prob >= 0.5 else 0
def load_data(filepath): def load_data(filepath):
"""加载数据并处理缺失值。""" """
从文件中加载数据。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = [] data = []
labels = [] labels = []
@@ -81,18 +116,15 @@ def load_data(filepath):
values = line.strip().replace('?', '0').split() values = line.strip().replace('?', '0').split()
try: try:
values = [float(v) for v in values] values = [float(v) for v in values]
if values[22] == 2 or values[22] == 3:
# 合并特征23的取值 labels.append(0)
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
labels.append(0) # 死亡
elif values[22] == 1: elif values[22] == 1:
labels.append(1) # 生存 labels.append(1)
else: else:
continue # 无效标签,丢弃 continue
# 用0填充缺失值 values = [0 if v == 0 else v for v in values]
values = [0 if v == 0 else v for v in values] # 直接用0填充 data.append(values[:2] + values[3:23])
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
except ValueError: except ValueError:
continue continue
@@ -101,43 +133,21 @@ def load_data(filepath):
return data, labels return data, labels
def preprocess_data(X):
"""特征标准化。"""
scaler = StandardScaler()
return scaler.fit_transform(X)
if __name__ == "__main__": if __name__ == "__main__":
# 加载数据集 # 加载训练集
X, y = load_data("./data/horse-colic.data") X_train, y_train = load_data("./data/horse-colic.data")
# 归一化数据 # 加载测试集
X = preprocess_data(X) X_test, y_test = load_data("./data/horse-colic.test")
# 使用 train_test_split 打乱并随机抽取数据 # 训练对率回归模型
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) other_params = {
'learning_rate': 0.01,
# K折交叉验证 'iterations': 1000,
k = 5 'lambda_reg': 0.01,
kf = KFold(n_splits=k, shuffle=True, random_state=42) 'batch_size': 32
accuracies = [] }
weights = train_logreg(X_train, y_train, other_params=other_params)
for train_index, val_index in kf.split(X_train):
X_train_kf, X_val_kf = X_train[train_index], X_train[val_index]
y_train_kf, y_val_kf = y_train[train_index], y_train[val_index]
# 训练逻辑回归模型,设置 batch size
batch_size = 32
weights = train_logreg(X_train_kf, y_train_kf, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=batch_size)
# 验证模型
val_predictions = [predict_logreg(X_val_kf[i], weights) for i in range(len(X_val_kf))]
accuracy = np.mean(val_predictions == y_val_kf)
accuracies.append(accuracy)
# 输出交叉验证的准确率和平均准确率
print(f"K折交叉验证得分: {accuracies}")
print(f"平均准确率: {np.mean(accuracies)}")
# 测试单个数据 # 测试单个数据
y_pred = predict_logreg(X_test[11], weights) y_pred = predict_logreg(X_test[11], weights)