diff --git a/function.py b/function.py index 09da6ad..a89a693 100644 --- a/function.py +++ b/function.py @@ -4,6 +4,11 @@ from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.linear_model import LogisticRegression + +id = "202210423130" +name = "董秋" + + def load_data(filepath): data = [] labels = [] @@ -32,12 +37,24 @@ def load_data(filepath): return np.array(data), np.array(labels) + def preprocess_data(X): # 特征标准化 scaler = StandardScaler() return scaler.fit_transform(X) + def train_logreg(X_train, y_train): + """ + 逻辑回归训练函数,使用网格搜索优化超参数。 + + Args: + - X_train (numpy array): 特征数据。 + - y_train (numpy array): 标签数据。 + + Returns: + - LogisticRegression: 训练得到的最佳模型。 + """ # 定义要调优的超参数范围 param_grid = { 'C': [0.001, 0.01, 0.1, 1, 10, 100], # 正则化参数 @@ -56,12 +73,15 @@ def train_logreg(X_train, y_train): return grid_search.best_estimator_ + def predict_logreg(inX, weights): """ 逻辑回归预测函数。 + Args: - inX (numpy array): 输入待分类的样本。 - weights (numpy array): 训练得到的权重。 + Returns: - int: 预测的分类标签。 """ @@ -69,6 +89,7 @@ def predict_logreg(inX, weights): prediction_prob = 1 / (1 + np.exp(-z)) return 1 if prediction_prob >= 0.5 else 0 + if __name__ == "__main__": # 加载数据集 X, y = load_data("./data/horse-colic.data")