diff --git a/function.py b/function.py index 29cd494..e8a5d58 100644 --- a/function.py +++ b/function.py @@ -25,7 +25,7 @@ from sklearn.model_selection import train_test_split, GridSearchCV id = "202210423221" name = "廖子豪" -def load_data(filepath, fit_scaler=False): +def load_data(filepath): data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0) labels = data[:, -1].astype(int) features = data[:, :-1] @@ -35,28 +35,12 @@ def load_data(filepath, fit_scaler=False): # 数据标准化 scaler = StandardScaler() - if fit_scaler: - features = scaler.fit_transform(features) - else: - features = scaler.transform(features) + features = scaler.fit_transform(features) - return features, labels, scaler + return features, labels -# 示例使用 -if __name__ == "__main__": - # 加载训练数据和测试数据 - X_train, y_train, scaler = load_data("./data/horse-colic.data", fit_scaler=True) - X_test, y_test, _ = load_data("./data/horse-colic.test", fit_scaler=False) # 使用相同的scaler - - # 训练模型 - model = train_logreg(X_train, y_train, random_state=42) - - # 进行预测 - y_pred = [predict_logreg(x, model) for x in X_test] - - # 计算准确率 - accuracy = np.mean(y_pred == y_test) - print(f"Test Accuracy: {accuracy:.2f}") +def train_logreg(X, y, random_state=42): + # 使用 GridSearchCV 进行参数调优 param_grid = {'C': [0.01, 0.1, 1, 10, 100], 'penalty': ['l1', 'l2']} model = LogisticRegression(solver='liblinear', random_state=random_state) grid_search = GridSearchCV(model, param_grid, cv=5) @@ -69,8 +53,8 @@ def predict_logreg(inX, model): # 示例使用 if __name__ == "__main__": # 加载训练数据和测试数据 - X_train, y_train, scaler = load_data("./data/horse-colic.data") - X_test, y_test, _ = load_data("./data/horse-colic.test") # 使用相同的scaler + X_train, y_train = load_data("./data/horse-colic.data") + X_test, y_test = load_data("./data/horse-colic.test") # 训练模型 model = train_logreg(X_train, y_train, random_state=42)