From e21fca47778bbdd7322d6f89f7bf114aeb0f54b9 Mon Sep 17 00:00:00 2001 From: wzy <675163717@qq.com> Date: Sun, 3 Nov 2024 16:15:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 184 +++++++++++++++++++++------------------------------- 1 file changed, 75 insertions(+), 109 deletions(-) diff --git a/function.py b/function.py index 06e1b31..2a245f5 100644 --- a/function.py +++ b/function.py @@ -28,140 +28,106 @@ name = "万子玉" # 这里写自己的代码实现 def sigmoid(z): - return 1 / (1 + np.exp(-z)) + return 1.0 / (1 + np.exp(-z)) -def train_logreg(X, y, learning_rate=0.1, iterations=2000, lambda_reg=0.01, batch_size=32): +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 - weights = np.random.randn(n) * 0.01 # 随机初始化权重,取较小值 + weights = np.random.randn(n) * np.sqrt(2. / n) # He初始化 + best_weights = weights.copy() + best_accuracy = 0 - for i in range(iterations): - # 每次迭代打乱数据 + for _ in range(iterations): indices = np.random.permutation(m) - X = X[indices] - y = y[indices] + X_shuffled = X[indices] + y_shuffled = y[indices] - for j in range(0, m, batch_size): # 按照 batch size 迭代 - X_batch = X[j:j + batch_size] - y_batch = y[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] - - # L2正则化 - gradient += (lambda_reg / m) * weights - - # 更新权重 + 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 - # 动态调整学习率,逐渐减小 - if i % 100 == 0: # 每100次迭代输出一次学习率 - 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() - return weights + # 动态调整学习率 + if _ % 100 == 0 and train_accuracy > 0.95: # 达到高准确率时减小学习率 + learning_rate *= 0.9 - """ - 对率回归训练函数。 + return best_weights - Args: - - X (numpy array): 特征数据。 - - y (numpy array): 标签数据。 - - other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。 +def predict_logreg(X, weights): + z = np.dot(X, weights) + h = sigmoid(z) + return np.where(h >= 0.5, 1, 0) - Returns: - - numpy array: 训练得到的权重。 - """ - - -def preprocess_data(X): - """特征标准化。""" - scaler = StandardScaler() - return scaler.fit_transform(X) - - """ - 对率回归预测函数。 - - Args: - - inX (numpy array): 输入待分类的样本。 - - weights (numpy array): 训练得到的权重。 - - Returns: - - int: 预测的分类标签。 - """ - -# 这里也写自己的代码实现 def load_data(filepath): - """加载数据并处理缺失值。""" - data = [] - labels = [] - + 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] - - # 合并特征23的取值 - if values[22] == 2 or values[22] == 3: # 特征23 - labels.append(0) # 死亡 - elif values[22] == 1: - labels.append(1) # 生存 - else: - continue # 无效标签,丢弃 - - # 用0填充缺失值 - values = [0 if v == 0 else v for v in values] # 直接用0填充 - data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23 - 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) - return data, labels - """ - 从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 + # 检查特征数量 + num_features = data.shape[1] - Args: - - directory (str): 数据文件路径。 + # 特征选择:去掉特征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) - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ + # 删除特征 + 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__": - # 加载数据集 + # 加载数据 X, y = load_data("./data/horse-colic.data") + + # 拆分训练集和验证集 + X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42) - # 归一化数据 - X = preprocess_data(X) + # 数据归一化 + scaler = MinMaxScaler() + X_train = scaler.fit_transform(X_train) + X_val = scaler.transform(X_val) - # 使用 train_test_split 打乱并随机抽取数据 - X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + # 训练模型 + final_weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000, batch_size=64, lambda_reg=0.1) - # K折交叉验证 - k = 5 - kf = KFold(n_splits=k, shuffle=True, random_state=42) - accuracies = [] + # 验证模型 + val_accuracy = accuracy(X_val, y_val, final_weights) + print(f"验证集的准确率: {val_accuracy:.4f}") - 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] + # 加载测试集 + X_test, y_test = load_data("./data/horse-colic.test") + X_test = scaler.transform(X_test) - # 训练逻辑回归模型,设置 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) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") \ No newline at end of file + # 测试模型 + final_test_accuracy = accuracy(X_test, y_test, final_weights) + print(f"最终测试集的准确率: {final_test_accuracy:.4f}") \ No newline at end of file