From 670cf4e4e3e365b9f3f90b1d2d199662439c54a9 Mon Sep 17 00:00:00 2001 From: 202210423104 <1961532386@qq.com> Date: Sun, 3 Nov 2024 16:32:07 +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 | 44 +++++++++++++++----------------------------- 1 file changed, 15 insertions(+), 29 deletions(-) diff --git a/function.py b/function.py index a0d5613..0e417d3 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,6 @@ import numpy as np -from sklearn.model_selection import train_test_split, cross_val_score from sklearn.ensemble import RandomForestClassifier +from sklearn.model_selection import train_test_split, cross_val_score from sklearn.preprocessing import PolynomialFeatures, StandardScaler id = "202210423104" @@ -12,15 +12,11 @@ def load_data(filepath): for line in file: line_data = line.strip().split() if line_data: - try: - data.append([float(x) if x != '?' else np.nan for x in line_data]) - except ValueError as e: - print(f"Error processing line: {line}. Error: {e}") + data.append([float(x) if x != '?' else np.nan for x in line_data]) data = np.array(data) data = np.nan_to_num(data, nan=np.nanmean(data, axis=0)) - - X = data[:, :-1] # 特征 - y = data[:, -1] # 标签 + X = data[:, :-1] + y = data[:, -1] return X, y def preprocess_data(X): @@ -31,32 +27,22 @@ def preprocess_data(X): return X_poly def train_logreg(X, y): - model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42) - X_processed = preprocess_data(X) # 预处理训练数据 + X_processed = preprocess_data(X) + model = RandomForestClassifier(n_estimators=200, max_depth=15, random_state=42) # 改变参数 model.fit(X_processed, y) - return model # 返回训练好的模型 + return model def predict_logreg(model, X): - X_processed = preprocess_data(X) # 预处理输入数据 - return model.predict(X_processed) # 返回预测结果 + if len(X.shape) == 1: + X = X.reshape(1, -1) + X_processed = preprocess_data(X) + return model.predict(X_processed)[0] if __name__ == "__main__": X, y = load_data("./data/horse-colic.data") - - # 划分数据集 - X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) - - # 训练模型 - model = train_logreg(X_train, y_train) - - # 预测 - y_pred = predict_logreg(model, X_test) # 调用预测函数 - - # 计算准确率 - accuracy = np.mean(y_pred == y_test) - print(f"测试出的正确率: {accuracy * 100:.2f}%") - + model = train_logreg(X, y) + # 交叉验证 - X_train_processed = preprocess_data(X_train) # 预处理训练数据 - cv_scores = cross_val_score(model, X_train_processed, y_train, cv=5) + X_processed = preprocess_data(X) + cv_scores = cross_val_score(model, X_processed, y, cv=5) print(f"交叉验证准确率: {np.mean(cv_scores) * 100:.2f}%")