From 5372fc90054c6815599f518aba56f2e195a192ea Mon Sep 17 00:00:00 2001 From: jack <2170067548@qq.com> Date: Sun, 3 Nov 2024 20:14:40 +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 | 61 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/function.py b/function.py index 67d61e0..99cc363 100644 --- a/function.py +++ b/function.py @@ -32,38 +32,53 @@ from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, classification_report -# 读取数据 -data_path = './data/horse-colic.data' -data = pd.read_csv(data_path, header=None, delim_whitespace=True, na_values='?') +def load_data(file_path): + # 读取数据 + data = pd.read_csv(file_path, header=None, delim_whitespace=True, na_values='?') + # 处理缺失值(用0填充) + data.fillna(0, inplace=True) + + # 选择特征和目标变量 + # 去掉特征3和特征24~28 + features = data.iloc[:, :-5].values # 假设最后一列是目标变量,前面的都是特征 + target = data.iloc[:, -1].values -# 处理缺失值(用0填充) -data.fillna(0, inplace=True) + # 将目标变量中的2和3合并为0 + target[target == 2] = 0 + target[target == 3] = 0 -# 选择特征和目标变量 -# 去掉特征3和特征24~28 -features = data.iloc[:, :-5].values # 假设最后一列是目标变量,前面的都是特征 -target = data.iloc[:, -1].values + # 将目标变量转换为二进制分类(0或1) + target = (target == 1).astype(int) -# 将目标变量中的2和3合并为0 -target[target == 2] = 0 -target[target == 3] = 0 + return features, target -# 将目标变量转换为二进制分类(0或1) -target = (target == 1).astype(int) +def train_logreg(X_train, y_train): + # 训练逻辑回归模型 + model = LogisticRegression(max_iter=1000) + model.fit(X_train, y_train) + return model -# 划分训练集和测试集 -X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42) +def predict_logreg(model, X_test): + # 进行预测 + return model.predict(X_test) -# 训练对率回归模型 -model = LogisticRegression(max_iter=1000) -model.fit(X_train, y_train) +# 主程序 +data_path = './data/horse-colic.data' +features, target = load_data(data_path) -# 预测并评估模型 -y_pred = model.predict(X_test) -accuracy = accuracy_score(y_test, y_pred) -report = classification_report(y_test, y_pred) +# 划分训练集和测试集 +X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42) + +# 训练模型 +model = train_logreg(X_train, y_train) + +# 预测并评估模型 +y_pred = predict_logreg(model, X_test) +accuracy = accuracy_score(y_test, y_pred) +report = classification_report(y_test, y_pred) print(f"Accuracy: {accuracy:.2f}") print("Classification Report:") print(report) +