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

This commit is contained in:
2024-11-03 13:02:57 +08:00
parent 19fb957f49
commit 0c3185cefc
+66 -92
View File
@@ -26,118 +26,92 @@ name = "廖运瑞"
# 这里写自己的代码实现 # 这里写自己的代码实现
import numpy as np def train_logreg(X, y, learning_rate=0.01, iterations=1000):
from sklearn.preprocessing import MinMaxScaler """
from sklearn.model_selection import train_test_split 对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- learning_rate (float): 学习率,默认为0.01。
- iterations (int): 迭代次数,默认为1000。
def sigmoid(z): Returns:
return 1.0 / (1 + np.exp(-z)) - numpy array: 训练得到的权重。
"""
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
def train_logreg(X, y, learning_rate=0.001, iterations=10000, batch_size=64, lambda_reg=0.1):
m, n = X.shape m, n = X.shape
weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化 weights = np.zeros(n)
best_weights = weights.copy() bias = 0 # 偏置项,可以合并到权重中处理,但这里单独处理
best_accuracy = 0
for _ in range(iterations): for _ in range(iterations):
indices = np.random.permutation(m) output = sigmoid(np.dot(X, weights) + bias)
X_shuffled = X[indices] error = y - output
y_shuffled = y[indices] weights += learning_rate * np.dot(X.T, error) / m
bias += learning_rate * np.sum(error) / m
for j in range(0, m, batch_size): # 如果需要返回偏置项,可以将其添加到权重数组的前面或作为单独的返回值
X_batch = X_shuffled[j:j + batch_size] # 这里为了与predict_logreg函数接口一致,我们选择不直接修改weights数组
y_batch = y_shuffled[j:j + batch_size] return weights, bias
gradient = compute_gradient(X_batch, y_batch, weights, lambda_reg)
weights -= learning_rate * gradient
# 计算训练集准确率 def predict_logreg(inX, weights, bias=0):
train_accuracy = accuracy(X, y, weights) """
if train_accuracy > best_accuracy: 对率回归预测函数。
best_accuracy = train_accuracy
best_weights = weights.copy()
# 动态调整学习率 Args:
if _ % 100 == 0 and train_accuracy > 0.95: # 达到高准确率时减小学习率 - inX (numpy array): 输入待分类的样本。
learning_rate *= 0.9 - weights (numpy array): 训练得到的权重。
- bias (float): 训练得到的偏置项,默认为0。
return best_weights Returns:
- int: 预测的分类标签(0或1)。
"""
z = np.dot(inX, weights) + bias
return 1 if sigmoid(z) >= 0.5 else 0
def sigmoid(z):
"""
Sigmoid激活函数。
def predict_logreg(X, weights): Args:
z = np.dot(X, weights) - z (float or numpy array): 输入值。
h = sigmoid(z)
return np.where(h >= 0.5, 1, 0)
Returns:
- float or numpy array: Sigmoid输出值。
"""
return 1 / (1 + np.exp(-z))
def load_data(filepath): 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) Args:
labels = np.array(labels) - filepath (str): 数据文件路径。
# 检查特征数量 Returns:
num_features = data.shape[1] - np.array: 特征数据。
- np.array: 标签数据。
"""
data = np.loadtxt(filepath, delimiter=' ')
X = data[:, 1:] # 特征数据,假设从第二列开始
y = data[:, 0] # 标签数据,假设在第一列
return X, y.astype(int) # 确保标签为整数类型
# 特征选择:去掉特征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)
# 删除特征
data = np.delete(data, indices_to_delete, axis=1)
# 将标签二分类化,特征23(索引22)取值2和3合并为0,其余为1
target_variable = np.where((labels == 2) | (labels == 3), 0, 1)
return data, target_variable
def accuracy(X, y, weights):
predictions = predict_logreg(X, weights)
return np.mean(predictions == y)
# 其余代码保持不变
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_train中添加一列全为1的列(或者使用上面的bias参数)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42) # 但为了与train_logreg函数接口一致,这里我们选择使用bias参数
# 如果选择将偏置项合并到权重中,则应该这样处理:
# 数据归一化 # X_train_with_bias = np.c_[np.ones((X_train.shape[0], 1)), X_train]
scaler = MinMaxScaler() # 并相应地修改train_logreg函数和predict_logreg函数的接口
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
# 训练模型
final_weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, batch_size=64, lambda_reg=0.1)
# 验证模型
val_accuracy = accuracy(X_val, y_val, final_weights)
print(f"验证集的准确率: {val_accuracy:.4f}")
# 加载测试集 # 加载测试集
X_test, y_test = load_data("./data/horse-colic.test") X_test, y_test = load_data("./data/horse-colic.test")
X_test = scaler.transform(X_test)
# 测试模型 # 训练对率回归模型
final_test_accuracy = accuracy(X_test, y_test, final_weights) weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
print(f"最终测试集的准确率: {final_test_accuracy:.4f}")
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights, bias)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")