import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import accuracy_score, mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from deap import base, creator, tools, algorithms
import numpy as np
from docx import Document
import matplotlib.pyplot as plt
import time
# 设置中文字体和负号显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 定义全局变量以便于调整和调试
DATA_SPLIT_RATIO = 0.2 # 数据划分比例(测试集占比)
DATA_SHUFFLE = True # 是否进行数据洗牌
CROSS_VALIDATION = True # 是否进行交叉验证
NGEN = 10 # 遗传算法迭代代数
POP_SIZE = 10 # 种群大小
MUTPB = 0.2 # 突变概率
CXPB = 0.5 # 交叉概率
def load_data():
# 读取Excel数据
data = pd.read_excel('附件1.xlsx') # 替换为您的数据文件
data = data.dropna() # 清除缺失值
return data
def pca_analysis(X):
# 数据标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 主成分分析(PCA)
pca = PCA(n_components=min(X_scaled.shape))
pca.fit(X_scaled)
explained_variance = pca.explained_variance_
explained_variance_ratio = pca.explained_variance_ratio_
cumulative_variance = np.cumsum(explained_variance_ratio)
# 总方差解释表格
print("总方差解释表格:")
print("成分\t特征根\t方差解释率(%)\t累积方差解释率(%)")
for i in range(len(explained_variance)):
print(f"{i + 1}\t{explained_variance[i]:.3f}\t{explained_variance_ratio[i] * 100:.3f}\t{cumulative_variance[i] * 100:.3f}")
return X_scaled, pca
def ask_user_for_choices():
print("\n请查看Excel数据的前几行:")
data = load_data()
print(data.head())
preprocess = input("数据是否已完成预处理(数据清洗和标准化)?(是/否): ").strip().lower()
if preprocess != '是':
print("请先进行数据预处理。")
return
task_type = input("请选择任务类型(分类/回归): ").strip().lower()
target_column = input("请指定Excel中的因变量列名: ").strip()
X = data.drop(columns=[target_column])
y = data[target_column]
if task_type == '分类':
if not pd.api.types.is_numeric_dtype(y) or len(y.unique()) <= 2:
model_class = RandomForestClassifier
metrics_function = accuracy_score
else:
print("分类任务需要目标变量为类别标签。")
主成分分析结合遗传算法优化的随机森林通用代码
于 2024-08-27 23:57:35 首次发布