generated from LufsX/Experiment-LogReg
This commit is contained in:
+19
-3
@@ -25,7 +25,7 @@ from sklearn.model_selection import train_test_split, GridSearchCV
|
||||
id = "202210423221"
|
||||
name = "廖子豪"
|
||||
|
||||
def load_data(filepath):
|
||||
def load_data(filepath, fit_scaler=False):
|
||||
data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0)
|
||||
labels = data[:, -1].astype(int)
|
||||
features = data[:, :-1]
|
||||
@@ -35,12 +35,28 @@ def load_data(filepath):
|
||||
|
||||
# 数据标准化
|
||||
scaler = StandardScaler()
|
||||
if fit_scaler:
|
||||
features = scaler.fit_transform(features)
|
||||
else:
|
||||
features = scaler.transform(features)
|
||||
|
||||
return features, labels, scaler
|
||||
|
||||
def train_logreg(X, y, random_state=42):
|
||||
# 使用 GridSearchCV 进行参数调优
|
||||
# 示例使用
|
||||
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}")
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user