使用SVM對心臟數據是否患病進行分類預測

作者簡介

杜嘉寶,男,西安工程大學電子信息學院,2024級研究生
研究方向:變壓器故障預警與檢測
電子郵件:djb857497378@gmail.com
王子謙,男,西安工程大學電子信息學院,2024級研究生,張宏偉人工智能課題組
研究方向:機器視覺與人工智能
電子郵件:1523018430@qq.com

在這篇文章中,我將分享如何使用支持向量機(SVM)算法對心臟病數據進行分類。整個流程包括數據加載、預處理、SMOTE過采樣、PCA降維、超參數調優、灰狼優化算法的使用等。通過這篇文章,希望你能夠了解如何通過集成不同技術實現更好的分類效果。

1. 安裝包的準備

首先,你需要安裝必要的Python庫。以下是一些主要的庫:
pip install numpy pandas scikit-learn imbalanced-learn matplotlib
這些庫提供了SVM、SMOTE過采樣、PCA降維以及其他常用的數據處理工具。

2. 數據集介紹

本次我們使用的是UCI心臟病數據集,包含多種與心臟病相關的特征,如年齡、性別、血壓、膽固醇水平等。數據集中的目標變量target有五個不同的類別,表示不同程度的心臟病。
通過加載數據,我們將其分為特征集(X)和目標值(y),并進行清洗(將?替換為0)。

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data"
columns = ["age", "sex", "cp", "trestbps", "chol", "fbs", "restecg", "thalach", "exang", "oldpeak", "slope", "ca", "thal", "target"]
features, target = load_data(url, columns)

3. SVM算法介紹

支持向量機(SVM)是一種強大的分類算法,尤其適合處理高維數據。它的目標是尋找一個超平面,將不同類別的樣本分開,并且最大化類別之間的間隔。在這篇文章中,我們使用SVC(支持向量分類)來實現心臟病數據的分類。

from sklearn.svm import SVC
svm_clf = SVC(kernel='rbf', C=1.0, gamma=0.1)
svm_clf.fit(X_train, y_train)

4. SMOTE算法介紹

在心臟病數據集中,類別不平衡問題較為嚴重。為了解決這個問題,我們使用了SMOTE(Synthetic Minority Over-sampling Technique)算法,通過生成合成樣本來平衡各個類別。

from imblearn.over_sampling import SMOTE
X_resampled, y_resampled = smote(X_train, y_train, sampling_strategy={2: 55, 3: 55, 4: 55})

5. GridSearch算法

為了尋找SVM模型的最佳超參數,我們使用了GridSearchCV進行超參數搜索。通過在不同的C和gamma值之間進行網格搜索,找出最優的組合。

from sklearn.model_selection import GridSearchCV
gridsearch(X_train, y_train, X_test, y_test)

6. PCA算法介紹

主成分分析(PCA)是降維的常用方法,可以在保留數據大部分信息的情況下,減少數據的維度。在本次任務中,我們使用PCA將數據維度降到95%的信息量。

from sklearn.decomposition import PCA
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)

7. 灰狼優化算法介紹

灰狼優化算法(Grey Wolf Optimizer, GWO)是一種模擬灰狼捕獵行為的優化算法。在這里,我們使用灰狼優化算法來尋找SVM模型的最佳超參數C和gamma。

def grey_wolf_optimizer(...):# 代碼實現見下文return alpha_pos, alpha_score

灰狼優化算法通過模擬灰狼群體的領導行為,幫助我們在搜索空間中找到最優解。

8. 實現流程

8.1 數據加載與預處理

首先,加載數據集,并進行數據清洗。然后,使用SMOTE算法處理類別不平衡問題。

(X_train, X_test, y_train, y_test) = train_test_split(features, target, test_size=0.3, random_state=1, stratify=target)
X_train, y_train = smote(X_train, y_train, sampling_strategy={2: 38, 3: 38, 4: 38})

8.2 數據標準化與PCA降維

使用StandardScaler對數據進行標準化處理,并使用PCA降維。

X_train, X_test = scaler(X_train, X_test)
pca = PCA(n_components=0.95)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)

8.3 模型訓練與優化

使用SVM進行訓練,并通過灰狼優化算法調整超參數。

print(grey_wolf_optimizer(0, 100, 10000, 100, 2, X_train, y_train, X_test, y_test))

8.4 可視化

使用Matplotlib進行數據可視化,展示PCA降維后的數據分布。

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_train[:, 0], X_train[:, 1], X_train[:, 2], c=y_train, cmap='viridis', alpha=0.7)

9. 源代碼

Utils.py
import numpy as np
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.decomposition import PCAdef scaler(x_train, x_test):standard_transform = StandardScaler()return standard_transform.fit_transform(x_train), standard_transform.fit_transform(x_test)def gridsearch(x_train, y_train, x_test, y_test):C = np.linspace(0,100,100)gamma = np.linspace(0,100,100)param_grid = {'C' : C,'gamma':gamma,'kernel':['rbf','poly']}svm_clf = SVC()grid_search = GridSearchCV(estimator=svm_clf,param_grid=param_grid,n_jobs=-1,cv=5,scoring='accuracy')grid_search.fit(x_train,y_train)print('網格中最優參數:',grid_search.best_params_)print('測試集的準確率:',grid_search.score(x_test,y_test))def apply_pca(data, n_components):# 標準化數據,使其均值為0,方差為1pca_scaler = StandardScaler()scaled_data = pca_scaler.fit_transform(data)# 進行 PCA 降維pca = PCA(n_components=n_components)reduced_data = pca.fit_transform(scaled_data)# 獲取解釋方差比例explained_variance = pca.explained_variance_ratio_return reduced_data, explained_variancedef grey_wolf_optimizer(lb, ub, n_wolves, max_iter, dim, x_train, y_train, x_test, y_test):# 定義目標函數def objective_function(C, gamma):clf = SVC(kernel='rbf', C=C, gamma=gamma, random_state=1)clf.fit(x_train, y_train)return 1 - clf.score(x_test, y_test)# 初始化狼群wolves = np.random.uniform(lb, ub, (n_wolves, dim))# 初始化 alpha、beta、delta 位置及適應度值alpha_pos = np.zeros(dim)alpha_score = float('inf')beta_pos = np.zeros(dim)beta_score = float('inf')delta_pos = np.zeros(dim)delta_score = float('inf')# 迭代優化for t in range(max_iter):# 計算當前狼群的適應度for i in range(n_wolves):wolves[i, :] = np.clip(wolves[i, :], lb, ub)  # 約束搜索范圍C = max(float(wolves[i, 0]), 1e-3)gamma = max(float(wolves[i, 1]),1e-3)fitness = objective_function(C, gamma)# 更新 alpha、beta、deltaif fitness < alpha_score:delta_score, delta_pos = beta_score, beta_pos.copy()beta_score, beta_pos = alpha_score, alpha_pos.copy()alpha_score, alpha_pos = fitness, wolves[i, :].copy()elif fitness < beta_score:delta_score, delta_pos = beta_score, beta_pos.copy()beta_score, beta_pos = fitness, wolves[i, :].copy()elif fitness < delta_score:delta_score, delta_pos = fitness, wolves[i, :].copy()# 計算系數 aa = 2 - t * (2 / max_iter)# 更新狼群位置for i in range(n_wolves):r1, r2 = np.random.rand(dim), np.random.rand(dim)A1 = 2 * a * r1 - aC1 = 2 * r2D_alpha = abs(C1 * alpha_pos - wolves[i, :])X1 = alpha_pos - A1 * D_alphar1, r2 = np.random.rand(dim), np.random.rand(dim)A2 = 2 * a * r1 - aC2 = 2 * r2D_beta = abs(C2 * beta_pos - wolves[i, :])X2 = beta_pos - A2 * D_betar1, r2 = np.random.rand(dim), np.random.rand(dim)A3 = 2 * a * r1 - aC3 = 2 * r2D_delta = abs(C3 * delta_pos - wolves[i, :])X3 = delta_pos - A3 * D_delta# 計算新位置wolves[i, :] = (X1 + X2 + X3) / 3print(f"Iteration {t+1}: Best C={alpha_pos[0]}, Best gamma={alpha_pos[1]}, Best fitness={1-alpha_score}")return alpha_pos, alpha_score
load_data.pyimport pandas as pd
import numpy as  np
from imblearn.over_sampling import SMOTEdef load_data(url, columns):# 讀取數據df = pd.read_csv(url, names=columns)df_cleaned = df.replace('?', 0)X = df_cleaned.iloc[:, :-1]  # 特征y = df_cleaned.iloc[:, -1]   # 目標值return X, ydef smote(x, y, sampling_strategy, random_state=1, k_neighbors=1):smote = SMOTE(random_state=random_state, sampling_strategy=sampling_strategy, k_neighbors=k_neighbors)x_resampled, y_resampled = smote.fit_resample(x, y)return x_resampled, y_resampledif __name__ == '__main__':url = "https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data"columns = ["age", "sex", "cp", "trestbps", "chol", "fbs", "restecg", "thalach","exang", "oldpeak", "slope", "ca", "thal", "target"]features, target = load_data(url, columns)labels, count = np.unique(target, return_counts=True)print('labels', labels, '  ', 'count:', count)sampling_strategy = {2: 55, 3: 55, 4: 55}smote = SMOTE(random_state=42, sampling_strategy=sampling_strategy, k_neighbors=1)features_resampled, target_resampled = smote.fit_resample(features, target)labels, count = np.unique(target_resampled, return_counts=True)
print('labels', labels, '  ', 'count:', count)train.py
from sklearn.model_selection import train_test_split
from load_data import load_data, smote
from utils import scaler, gridsearch,grey_wolf_optimizer
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCAurl = "https://archive.ics.uci.edu/ml/machine-learning-databases/heart-disease/processed.cleveland.data"
columns = ["age", "sex", "cp", "trestbps", "chol", "fbs", "restecg", "thalach", "exang", "oldpeak", "slope", "ca", "thal", "target"]
features, target = load_data(url, columns)
(X_train,X_test,y_train,y_test) = train_test_split(features, target,test_size=0.3,random_state=1,stratify=target)
labels, count = np.unique(y_train, return_counts=True)
print('labels', labels, '  ', 'count:', count)
sampling_strategy = {2: 38, 3: 38, 4: 38}
X_train, y_train = smote(X_train, y_train,sampling_strategy)
labels, count = np.unique(y_train, return_counts=True)
print('labels', labels, '  ', 'count:', count)
X_train, X_test = scaler(X_train,X_test)
pca = PCA(n_components=0.95)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_train[:, 0], X_train[:, 1], X_train[:, 2], c=y_train, cmap='viridis', alpha=0.7)ax.set_xlabel("Principal Component 1")
ax.set_ylabel("Principal Component 2")
ax.set_zlabel("Principal Component 3")
ax.set_title("PCA 3D Scatter Plot")
plt.show()
print(grey_wolf_optimizer(0,100,10000,100,2,X_train,y_train,X_test,y_test))

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/901875.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/901875.shtml
英文地址,請注明出處:http://en.pswp.cn/news/901875.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Node做BFF中間層架構優化前端開發體驗并提升系統整體性能。

文章目錄 1. BFF 層的定位2. 技術選型3. 架構設計3.1 分層設計3.2 示例架構 4. 核心功能實現4.1 數據聚合4.2 權限校驗4.3 緩存優化 5、實戰示例1. 場景說明2. ECharts 數據格式要求3. BFF 層實現步驟3.1 接收前端參數3.2 調用后端服務獲取數據 4. 前端使用 總結 在使用 Node.j…

文件系統 軟硬連接

&#x1f33b;個人主頁&#xff1a;路飛雪吖~ &#x1f320;專欄&#xff1a;Linux 目錄 一、理解文件系統 &#x1f320;磁盤結構 二、軟硬連接 &#x1f31f;軟硬鏈接 &#x1f320;軟鏈接&#xff1a; &#x1f320;硬鏈接&#xff1a; &#x1f31f;理解軟硬鏈接的應…

單片機 | 基于51單片機的自動循跡小車設計

以下是一個基于51單片機的自動循跡小車設計詳解,包含原理、公式和完整代碼: 一、系統原理 核心模塊: 傳感器:紅外對管(TCRT5000)x4主控芯片:STC89C52RC(51單片機)電機驅動:L298N驅動模塊電源:7.4V鋰電池(電機) + 5V穩壓(單片機)工作原理: 紅外對管發射紅外線,…

2025.04.17【Stacked area】| 生信數據可視化:堆疊區域圖深度解析

文章目錄 生信數據可視化&#xff1a;堆疊區域圖深度解析堆疊面積圖簡介為什么使用堆疊面積圖如何使用R語言創建堆疊面積圖安裝和加載ggplot2包創建堆疊面積圖的基本步驟示例代碼 解讀堆疊面積圖堆疊面積圖的局限性實際應用案例示例&#xff1a;基因表達量隨時間變化 結論 生信…

基于單片機的智能養生油炸爐系統設計與實現

標題:基于單片機的智能養生油炸爐系統設計與實現 內容:1.摘要 本文針對傳統油炸爐功能單一、無法滿足現代養生需求的問題&#xff0c;設計并實現了基于單片機的智能養生油炸爐系統。通過采用STC89C52單片機作為控制核心&#xff0c;結合溫度傳感器、液位傳感器、繼電器等硬件&…

QML與C++:基于ListView調用外部模型進行增刪改查(附自定義組件)

目錄 引言相關閱讀項目結構文件組織 核心技術實現1. 數據模型設計聯系人項目類 (datamodel.h)數據模型類 (datamodel.h)數據模型實現 (datamodel.cpp) 2. 主程序入口點 (main.cpp)3. 主界面設計 (Main.qml)4. 聯系人對話框 (ContactDialog.qml)5. 自定義組件CustomTextField.qm…

【MySQL】事務ACID理解記憶

事務的 ACID 特性詳解 數據庫中的 事務&#xff08;Transaction&#xff09; 是一組操作的集合&#xff0c;這些操作要么全部執行&#xff0c;要么全部不執行。為了保證事務可靠執行&#xff0c;必須滿足 ACID 四大特性&#xff1a; 特性英文縮寫簡要說明原子性Atomicity事務…

MYSQL “Too Many Connections“ 錯誤解決

1.查詢當前連接數 show status like "Threads_connected"; 2.查詢數據庫最大連接數 show variables like "max_connections" 3.查詢所有活動連接 show processlist; 4.根據查詢結果觀察是否有長時間未被釋放的連接 參數解釋 : 字段說明id連接的唯一…

Python爬蟲實戰:基于 Scrapy 框架的微博數據爬取研究

一、引言 1.1 研究背景 在當今數字化時代,社交媒體已成為信息傳播和公眾交流的重要平臺。微博作為國內極具影響力的社交媒體之一,每日產生海量的用戶生成內容,涵蓋新聞資訊、社交互動、娛樂八卦、熱點話題討論等多個領域。這些數據不僅反映了公眾的興趣偏好、情感態度和社…

貓咪如廁檢測與分類識別系統系列【九】視頻檢測區域在線繪制+支持攝像頭+網絡攝像頭+整體構建【上】

前情提要 家里養了三只貓咪&#xff0c;其中一只布偶貓經常出入廁所。但因為平時忙于學業&#xff0c;沒法時刻關注牠的行為。我知道貓咪的如廁頻率和時長與健康狀況密切相關&#xff0c;頻繁如廁可能是泌尿問題&#xff0c;停留過久也可能是便秘或不適。為了更科學地了解牠的如…

【AI插件開發】Notepad++ AI插件開發實踐:支持多平臺多模型

引言 上篇文章我們的Notepad插件介紹到Dock窗口集成&#xff0c;本篇將繼續完善插件功能&#xff0c;主要包括兩個部分&#xff1a; 支持多平臺、多模型支持多種授權驗證、接口類型 一、多平臺 原先的配置項很簡單&#xff1a; // PluginConf.h class PlatformConf { publ…

【C#】Socket通信的使用

在C#中&#xff0c;Socket通信是一種用于實現網絡通信的底層技術。通過Socket&#xff0c;程序可以在網絡上與其他設備進行數據交換。以下是如何使用C#中的System.Net.Sockets命名空間來實現Socket通信的詳細步驟。 1. Socket通信的基本概念 Socket: 一個Socket是網絡通信的端…

2024年第九屆團隊程序設計天梯賽c++題解L1-L3-1(附PTA網址)

L1-1 編程解決一切 5分 L1-097 編程解決一切 - 團體程序設計天梯賽-練習集 (pintia.cn)https://pintia.cn/problem-sets/994805046380707840/exam/problems/type/7?problemSetProblemId1781658570803388416 #include<bits/stdc.h> #define int long long using namesp…

ICMAN防水觸摸芯片 - 復雜環境下精準交互,提升觸控體驗

▍核心優勢 ◆ 超強抗干擾能力 ◆ 工業級設計&#xff0c;一致性和穩定性好 ▍提供場景化解決方案 【智能廚電矩陣】抽油煙機檔位調節 | 電磁爐火力觸控 | 洗碗機模式切換 【衛浴設備方案】淋浴房霧化玻璃控制 | 智能馬桶觸控面板 | 浴缸水位感應 【工業控制應用】儀器儀…

Golang|抽獎相關

文章目錄 抽獎核心算法生成抽獎大轉盤抽獎接口實現 抽獎核心算法 我們可以根據 單商品庫存量/總商品庫存量 得到每個商品被抽中的概率&#xff0c;可以想象這樣一條 0-1 的數軸&#xff0c;數軸上的每一段相當于一種商品&#xff0c;概率之和為1。 抽獎時&#xff0c;我們會生…

OpenCV 圖形API(43)顏色空間轉換-----將 BGR 圖像轉換為 LUV 色彩空間函數BGR2LUV()

操作系統&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 編程語言&#xff1a;C11 算法描述 將圖像從BGR色彩空間轉換為LUV色彩空間。 該函數將輸入圖像從BGR色彩空間轉換為LUV。B、G和R通道值的傳統范圍是0到255。 輸出圖像必須是8位無符…

【Python】用Python寫一個俄羅斯方塊玩玩

【Python】用Python寫一個俄羅斯方塊玩玩 一、引言1.成品效果展示 二、思考準備1.思考設計2.代碼設計2.1 游戲頁面2.2 控件設計2.2.1 方塊生成2.2.2 方塊碰撞2.2.3 方塊消融2.2.4 游戲主循環2.2.5 游戲窗口 三、游戲完整版 一、引言 今日看到侄子在玩游戲&#xff0c;湊近一看…

維港首秀!沃飛長空AE200亮相香港特別行政區

4月13日-16日&#xff0c;第三屆香港國際創科展在香港會議展覽中心盛大舉辦。 作為國內領先、國際一流的eVTOL主機廠&#xff0c;沃飛長空攜旗下AE200批產構型登陸國際舞臺&#xff0c;以前瞻性的創新技術與商業化應用潛力&#xff0c;吸引了來自全球17個國家及地區的行業領袖…

Openfein實現遠程調用的方法(實操)

文章目錄 環境準備一、URL中接收參數二、接收一個參數三、接收多個參數四、傳遞對象五、傳遞JSON格式數據 環境準備 下面的配置&#xff0c;服務調用方加入即可。 依賴導入&#xff1a; <!-- openfeign依賴--><dependency><groupId>org.springframe…

Bright+Data網頁解鎖器:旅游行業數據革命的“隱形引擎”

在數字經濟浪潮中&#xff0c;旅游行業正經歷前所未有的變革。當消費者指尖滑動間完成跨國酒店預訂&#xff0c;當航空公司每秒調整萬次艙位價格&#xff0c;背后是一場無聲的數據戰爭。而在這場戰爭中&#xff0c;BrightData網頁解鎖器正成為旅游企業破局的關鍵武器——它像一…