From a9fb7b5eaa36d421478d083fe085c15c59dac143 Mon Sep 17 00:00:00 2001 From: wzy <675163717@qq.com> Date: Sat, 26 Oct 2024 12:20:04 +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 | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/function.py b/function.py index e58ee0c..4388d14 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,6 @@ # function.py import numpy as np -from sklearn.model_selection import train_test_split +import random """ 实验说明: @@ -68,10 +68,12 @@ def train_logreg(X, y, learning_rate=0.001, iterations=1000, batch_size=32, init """ -def evaluate_model(X_val, y_val, weights): - predictions = np.array([predict_logreg(x, weights) for x in X_val]) - accuracy = np.mean(predictions == y_val) - return accuracy +def predict_logreg(inX, weights): + inX = np.insert(inX, 0, 1) # 添加偏置项 + z = np.dot(inX, weights) + h = sigmoid(z) + return 1 if h >= 0.5 else 0 + """ 对率回归预测函数。 @@ -83,6 +85,28 @@ def evaluate_model(X_val, y_val, weights): Returns: - int: 预测的分类标签。 """ +def evaluate_model(X_val, y_val, weights): + predictions = np.array([predict_logreg(x, weights) for x in X_val]) + accuracy = np.mean(predictions == y_val) + return accuracy + +def split_train_val(X, y, val_size=0.2): + # 确保数据是随机打乱的 + shuffled_indices = list(range(X.shape[0])) + random.shuffle(shuffled_indices) + X_shuffled = X[shuffled_indices] + y_shuffled = y[shuffled_indices] + + # 计算验证集的大小 + val_count = int(X.shape[0] * val_size) + + # 分割数据集 + X_val = X_shuffled[:val_count] + y_val = y_shuffled[:val_count] + X_train = X_shuffled[val_count:] + y_train = y_shuffled[val_count:] + + return X_train, X_val, y_train, y_val # 这里也写自己的代码实现 @@ -119,7 +143,7 @@ def load_data(filepath): 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_train, X_val, y_train, y_val = split_train_val(X, y) # 模型调优参数 learning_rates = [0.01, 0.001, 0.0001]