比價網(wǎng)站開發(fā)湘潭專業(yè)sem優(yōu)化
鶴壁市浩天電氣有限公司
2026/01/24 09:03:48
比價網(wǎng)站開發(fā),湘潭專業(yè)sem優(yōu)化,原畫培訓價格一般是多少,寧波是哪個省浙大疏錦行
算法全過程如下#xff1a;
# 先運行之前預(yù)處理好的代碼
import pandas as pd
import pandas as pd #用于數(shù)據(jù)處理和分析#xff0c;可處理表格數(shù)據(jù)。
import numpy as np #用于數(shù)值計算#xff0c;提供了高效的數(shù)組操作。
import matplotlib.pyplot as…浙大疏錦行算法全過程如下# 先運行之前預(yù)處理好的代碼 import pandas as pd import pandas as pd #用于數(shù)據(jù)處理和分析可處理表格數(shù)據(jù)。 import numpy as np #用于數(shù)值計算提供了高效的數(shù)組操作。 import matplotlib.pyplot as plt #用于繪制各種類型的圖表 import seaborn as sns #基于matplotlib的高級繪圖庫能繪制更美觀的統(tǒng)計圖形。 import warnings warnings.filterwarnings(ignore) #忽略警告信息保持輸出清潔。 # 設(shè)置中文字體解決中文顯示問題 plt.rcParams[font.sans-serif] [SimHei] # Windows系統(tǒng)常用黑體字體 plt.rcParams[axes.unicode_minus] False # 正常顯示負號 data pd.read_csv(E:\study\PythonStudy\python60-days-challenge-master\data.csv) #讀取數(shù)據(jù) # 先篩選字符串變量 discrete_features data.select_dtypes(include[object]).columns.tolist() # Home Ownership 標簽編碼 home_ownership_mapping { Own Home: 1, Rent: 2, Have Mortgage: 3, Home Mortgage: 4 } data[Home Ownership] data[Home Ownership].map(home_ownership_mapping) # Years in current job 標簽編碼 years_in_job_mapping { 1 year: 1, 1 year: 2, 2 years: 3, 3 years: 4, 4 years: 5, 5 years: 6, 6 years: 7, 7 years: 8, 8 years: 9, 9 years: 10, 10 years: 11 } data[Years in current job] data[Years in current job].map(years_in_job_mapping) # Purpose 獨熱編碼記得需要將bool類型轉(zhuǎn)換為數(shù)值 data pd.get_dummies(data, columns[Purpose]) data2 pd.read_csv(E:\study\PythonStudy\python60-days-challenge-master\data.csv) # 重新讀取數(shù)據(jù)用來做列名對比 list_final [] # 新建一個空列表用于存放獨熱編碼后新增的特征名 for i in data.columns: if i not in data2.columns: list_final.append(i) # 這里打印出來的就是獨熱編碼后的特征名 for i in list_final: data[i] data[i].astype(int) # 這里的i就是獨熱編碼后的特征名 # Term 0 - 1 映射 term_mapping { Short Term: 0, Long Term: 1 } data[Term] data[Term].map(term_mapping) data.rename(columns{Term: Long Term}, inplaceTrue) # 重命名列 continuous_features data.select_dtypes(include[int64, float64]).columns.tolist() #把篩選出來的列名轉(zhuǎn)換成列表 # 連續(xù)特征用中位數(shù)補全 for feature in continuous_features: mode_value data[feature].mode()[0] #獲取該列的眾數(shù)。 data[feature].fillna(mode_value, inplaceTrue) #用眾數(shù)填充該列的缺失值inplaceTrue表示直接在原數(shù)據(jù)上修改。 # 最開始也說了 很多調(diào)參函數(shù)自帶交叉驗證甚至是必選的參數(shù)你如果想要不交叉反而實現(xiàn)起來會麻煩很多 # 所以這里我們還是只劃分一次數(shù)據(jù)集 from sklearn.model_selection import train_test_split X data.drop([Credit Default], axis1) # 特征axis1表示按列刪除 y data[Credit Default] # 標簽 # 按照8:2劃分訓練集和測試集 X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.2, random_state42) # 80%訓練集20%測試集 from sklearn.ensemble import RandomForestClassifier #隨機森林分類器 from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # 用于評估分類器性能的指標 from sklearn.metrics import classification_report, confusion_matrix #用于生成分類報告和混淆矩陣 import warnings #用于忽略警告信息 warnings.filterwarnings(ignore) # 忽略所有警告信息 # --- 1. 默認參數(shù)的隨機森林 --- # 評估基準模型這里確實不需要驗證集 print(--- 1. 默認參數(shù)隨機森林 (訓練集 - 測試集) ---) import time # 這里介紹一個新的庫time庫主要用于時間相關(guān)的操作因為調(diào)參需要很長時間記錄下會幫助后人知道大概的時長 start_time time.time() # 記錄開始時間 rf_model RandomForestClassifier(random_state42) rf_model.fit(X_train, y_train) # 在訓練集上訓練 rf_pred rf_model.predict(X_test) # 在測試集上預(yù)測 end_time time.time() # 記錄結(jié)束時間 print(f訓練與預(yù)測耗時: {end_time - start_time:.4f} 秒) print(
默認隨機森林 在測試集上的分類報告) print(classification_report(y_test, rf_pred)) print(默認隨機森林 在測試集上的混淆矩陣) print(confusion_matrix(y_test, rf_pred)) # 安裝并導入 DEAP 庫 # !pip install deap import random from deap import base, creator, tools, algorithms # 4.2 定義問題個體與適應(yīng)度 # 定義適應(yīng)度我們需要最大化兩個目標所以權(quán)重都設(shè)為 1.0 # weights(1.0, 1.0) 表示我們希望同時最大化這兩個值 creator.create(FitnessMulti, base.Fitness, weights(1.0, 1.0)) # 定義個體每個個體包含一組隨機森林的超參數(shù) # 我們選擇優(yōu)化4個關(guān)鍵超參數(shù) # 1. n_estimators (樹的數(shù)量) # 2. max_depth (樹的最大深度) # 3. min_samples_split (節(jié)點分裂所需的最小樣本數(shù)) # 4. min_samples_leaf (葉節(jié)點所需的最小樣本數(shù)) creator.create(Individual, list, fitnesscreator.FitnessMulti) # 4.3 創(chuàng)建工具箱 (Toolbox) toolbox base.Toolbox() # 定義每個基因超參數(shù)的生成方式 # n_estimators: 整數(shù)范圍 [50, 300] toolbox.register(attr_n_estimators, random.randint, 50, 300) # max_depth: 整數(shù)范圍 [5, 50] toolbox.register(attr_max_depth, random.randint, 5, 50) # min_samples_split: 整數(shù)范圍 [2, 20] toolbox.register(attr_min_samples_split, random.randint, 2, 20) # min_samples_leaf: 整數(shù)范圍 [1, 20] toolbox.register(attr_min_samples_leaf, random.randint, 1, 20) # 將基因組合成個體 # n1 表示每個函數(shù)調(diào)用1次生成一個完整的個體 toolbox.register(individual, tools.initCycle, creator.Individual, (toolbox.attr_n_estimators, toolbox.attr_max_depth, toolbox.attr_min_samples_split, toolbox.attr_min_samples_leaf), n1) # 定義種群 toolbox.register(population, tools.initRepeat, list, toolbox.individual) # 4.4 定義評估函數(shù) def evaluate_rf(individual): 評估函數(shù)接收一個個體超參數(shù)組合返回其在測試集上的精確率, 召回率 # 從個體中解析超參數(shù) n_estimators, max_depth, min_samples_split, min_samples_leaf individual # 創(chuàng)建并訓練隨機森林模型 rf RandomForestClassifier( n_estimatorsn_estimators, max_depthmax_depth, min_samples_splitmin_samples_split, min_samples_leafmin_samples_leaf, random_state42, n_jobs-1 # 使用所有可用的CPU核心 ) rf.fit(X_train, y_train) # 在測試集上進行預(yù)測 predictions rf.predict(X_test) # 計算精確率和召回率 # precision_score 和 recall_score 默認計算正類標簽為1的指標 precision precision_score(y_test, predictions) recall recall_score(y_test, predictions) # 返回評估結(jié)果注意必須是元組 return (precision, recall) # 注冊評估函數(shù)、交叉、變異和選擇算子 toolbox.register(evaluate, evaluate_rf) toolbox.register(mate, tools.cxTwoPoint) # 兩點交叉 toolbox.register(mutate, tools.mutUniformInt, low[50, 5, 2, 1], up[300, 50, 20, 20], indpb0.2) # 均勻整數(shù)變異 toolbox.register(select, tools.selNSGA2) # NSGA-II 選擇算法 def run_optimization(): 運行NSGA-II多目標優(yōu)化算法 這個函數(shù)的作用 1. 設(shè)置統(tǒng)計信息收集器用于監(jiān)控優(yōu)化過程 2. 創(chuàng)建初始種群 3. 運行遺傳算法進行多目標優(yōu)化 4. 返回最終的優(yōu)化結(jié)果 # 統(tǒng)計信息收集器 - 用于監(jiān)控優(yōu)化過程 # 這些統(tǒng)計信息幫助我們了解算法的收斂情況 stats tools.Statistics(lambda ind: ind.fitness.values) # 獲取每個個體的適應(yīng)度值 # 注冊統(tǒng)計函數(shù) - 對每一代種群計算這些統(tǒng)計量 stats.register(avg, np.mean, axis0) # 平均值看整體水平趨勢 stats.register(std, np.std, axis0) # 標準差看種群多樣性 stats.register(min, np.min, axis0) # 最小值看最差個體表現(xiàn) stats.register(max, np.max, axis0) # 最大值看最好個體表現(xiàn) print( 開始多目標優(yōu)化...) print( 將監(jiān)控以下統(tǒng)計信息) print( ? avg: 每一代的平均精確率和召回率) print( ? std: 種群的多樣性程度) print( ? min: 最差個體的表現(xiàn)) print( ? max: 最好個體的表現(xiàn)) print() # 初始化種群 pop toolbox.population(n50) # 創(chuàng)建50個隨機個體作為初始種群 print(f初始化種群完成種群大小: {len(pop)}) # 運行NSGA-II算法進行演化 print(開始演化過程...) start_time time.time() # eaMuPlusLambda 是 DEAP 提供的 (μ λ) 演化策略 # μ: 父代數(shù)量λ: 子代數(shù)量 final_pop, logbook algorithms.eaMuPlusLambda( pop, toolbox, mu50, # 父代種群大小 lambda_50, # 每一代產(chǎn)生的子代數(shù)量 cxpb0.7, # 交叉概率 (70%的個體會進行交叉) mutpb0.2, # 變異概率 (20%的個體會發(fā)生變異) ngen20, # 演化代數(shù) (為了演示設(shè)置得較小) statsstats, # 統(tǒng)計信息收集器 halloffameNone, # 不使用名人堂 verboseTrue # 顯示每一代的進化過程 ) end_time time.time() print(f
多目標優(yōu)化完成) print(f總耗時: {end_time - start_time:.2f} 秒) print(f最終種群大小: {len(final_pop)}) return final_pop # 運行優(yōu)化 print( * 60) print(開始運行多目標優(yōu)化算法) print( * 60) final_pop run_optimization() # 5.1 提取帕累托前沿的解 # 使用 tools.selBest 可以方便地從種群中選出最優(yōu)的個體 # 在多目標優(yōu)化中它會返回所有非支配解 pareto_front tools.selBest(final_pop, klen(final_pop)) print(f找到了 {len(pareto_front)} 個帕累托最優(yōu)解。) print(
部分最優(yōu)解 (超參數(shù)) 及其對應(yīng)的 (精確率, 召回率):) print(- * 60) print(n_est, max_d, min_split, min_leaf | Precision | Recall) print(- * 60) # 存儲結(jié)果用于繪圖 pareto_points [] for ind in pareto_front: params ind fitness ind.fitness.values pareto_points.append(fitness) print(f{str(params):30} | {fitness[0]:.5f} | {fitness[1]:.5f}) # 轉(zhuǎn)換為numpy數(shù)組方便處理 pareto_points np.array(pareto_points) # 5.2 可視化帕累托前沿 plt.figure(figsize(10, 7)) # 繪制基準模型 base_precision precision_score(y_test, rf_pred) base_recall recall_score(y_test, rf_pred) plt.scatter(base_recall, base_precision, markers, colorr, s150, labelf基準模型 (Recall{base_recall:.3f}, Precision{base_precision:.3f}), zorder3) # 繪制帕累托前沿 plt.scatter(pareto_points[:, 1], pareto_points[:, 0], facecolorsnone, edgecolorsb, s80, label帕累托前沿解, zorder2) plt.title(多目標優(yōu)化結(jié)果帕累托前沿, fontsize16) plt.xlabel(召回率 (Recall), fontsize12) plt.ylabel(精確率 (Precision), fontsize12) plt.grid(True, linestyle--, alpha0.6) plt.legend() plt.show()結(jié)果通過多目標優(yōu)化我們不再是得到一個單一的“最佳”模型而是得到了一系列“各有所長”的優(yōu)秀模型這為實際應(yīng)用提供了更大的靈活性。