generated from LufsX/Experiment-LogReg
This commit is contained in:
+7
-23
@@ -25,7 +25,7 @@ from sklearn.model_selection import train_test_split, GridSearchCV
|
|||||||
id = "202210423221"
|
id = "202210423221"
|
||||||
name = "廖子豪"
|
name = "廖子豪"
|
||||||
|
|
||||||
def load_data(filepath, fit_scaler=False):
|
def load_data(filepath):
|
||||||
data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0)
|
data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0)
|
||||||
labels = data[:, -1].astype(int)
|
labels = data[:, -1].astype(int)
|
||||||
features = data[:, :-1]
|
features = data[:, :-1]
|
||||||
@@ -35,28 +35,12 @@ def load_data(filepath, fit_scaler=False):
|
|||||||
|
|
||||||
# 数据标准化
|
# 数据标准化
|
||||||
scaler = StandardScaler()
|
scaler = StandardScaler()
|
||||||
if fit_scaler:
|
features = scaler.fit_transform(features)
|
||||||
features = scaler.fit_transform(features)
|
|
||||||
else:
|
|
||||||
features = scaler.transform(features)
|
|
||||||
|
|
||||||
return features, labels, scaler
|
return features, labels
|
||||||
|
|
||||||
# 示例使用
|
def train_logreg(X, y, random_state=42):
|
||||||
if __name__ == "__main__":
|
# 使用 GridSearchCV 进行参数调优
|
||||||
# 加载训练数据和测试数据
|
|
||||||
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']}
|
param_grid = {'C': [0.01, 0.1, 1, 10, 100], 'penalty': ['l1', 'l2']}
|
||||||
model = LogisticRegression(solver='liblinear', random_state=random_state)
|
model = LogisticRegression(solver='liblinear', random_state=random_state)
|
||||||
grid_search = GridSearchCV(model, param_grid, cv=5)
|
grid_search = GridSearchCV(model, param_grid, cv=5)
|
||||||
@@ -69,8 +53,8 @@ def predict_logreg(inX, model):
|
|||||||
# 示例使用
|
# 示例使用
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练数据和测试数据
|
# 加载训练数据和测试数据
|
||||||
X_train, y_train, scaler = load_data("./data/horse-colic.data")
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
X_test, y_test, _ = load_data("./data/horse-colic.test") # 使用相同的scaler
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
# 训练模型
|
# 训练模型
|
||||||
model = train_logreg(X_train, y_train, random_state=42)
|
model = train_logreg(X_train, y_train, random_state=42)
|
||||||
|
|||||||
Reference in New Issue
Block a user