diff --git a/function.py b/function.py index 0e76974..185680b 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,7 @@ import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import PolynomialFeatures, StandardScaler +from sklearn.model_selection import train_test_split, cross_val_score id = "202210423104" name = "张钦诚" @@ -35,12 +36,29 @@ def train_logreg(X, y): model.fit(X_processed, y) return model # 返回训练好的模型 -def predict_logreg(X, model): - # 确保输入数据是一个 numpy 数组 - if len(X.shape) == 1: - X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n),符合模型的输入要求 - X_processed = preprocess_data(X) # 预处理测试数据 - return model.predict(X_processed)[0] # 确保 model 是训练好的模型 +def predict_logreg(model, X): + X_processed = preprocess_data(X.reshape(1, -1)) # 预处理单个测试样本 + 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 = [] + for sample in X_test: + y_pred.append(predict_logreg(model, sample)) + + # 计算准确率 + accuracy = np.mean(y_pred == y_test) + print(f"测试出的正确率: {accuracy * 100:.2f}%") + + # 交叉验证 + cv_scores = cross_val_score(model, preprocess_data(X_train), y_train, cv=5) + print(f"交叉验证准确率: {np.mean(cv_scores) * 100:.2f}%")