【阿旭机器学习实战】【34】使用SVM检测蘑菇是否有毒--支持向量机

简介: 【阿旭机器学习实战】【34】使用SVM检测蘑菇是否有毒--支持向量机

1. 导入并查看数据

关注GZH:阿旭算法与机器学习,回复:“ML34”即可获取本文数据集、源码与项目文档

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# 导入数据
mush_df = pd.read_csv('mushrooms.csv')
mush_df.head()
class cap-shape cap-surface cap-color bruises odor gill-attachment gill-spacing gill-size gill-color ... stalk-surface-below-ring stalk-color-above-ring stalk-color-below-ring veil-type veil-color ring-number ring-type spore-print-color population habitat
0 p x s n t p f c n k ... s w w p w o p k s u
1 e x s y t a f c b k ... s w w p w o p n n g
2 e b s w t l f c b n ... s w w p w o p n n m
3 p x y w t p f c n n ... s w w p w o p k s u
4 e x s g f n f w b k ... s w w p w o e n a g

5 rows × 23 columns

每个特征的含义如下:

  1. cap-shape: bell=b,conical=c,convex=x,flat=f, knobbed=k,sunken=s
  2. cap-surface: fibrous=f,grooves=g,scaly=y,smooth=s
  3. cap-color: brown=n,buff=b,cinnamon=c,gray=g,green=r, pink=p,purple=u,red=e,white=w,yellow=y
  4. bruises?: bruises=t,no=f
  5. odor: almond=a,anise=l,creosote=c,fishy=y,foul=f, musty=m,none=n,pungent=p,spicy=s
  6. gill-attachment: attached=a,descending=d,free=f,notched=n
  7. gill-spacing: close=c,crowded=w,distant=d
  8. gill-size: broad=b,narrow=n
  9. gill-color: black=k,brown=n,buff=b,chocolate=h,gray=g, green=r,orange=o,pink=p,purple=u,red=e, white=w,yellow=y
  10. stalk-shape: enlarging=e,tapering=t
  11. stalk-root: bulbous=b,club=c,cup=u,equal=e, rhizomorphs=z,rooted=r,missing=?
  12. stalk-surface-above-ring: fibrous=f,scaly=y,silky=k,smooth=s
  13. stalk-surface-below-ring: fibrous=f,scaly=y,silky=k,smooth=s
  14. stalk-color-above-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o, pink=p,red=e,white=w,yellow=y
  15. stalk-color-below-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o, pink=p,red=e,white=w,yellow=y
  16. veil-type: partial=p,universal=u
  17. veil-color: brown=n,orange=o,white=w,yellow=y
  18. ring-number: none=n,one=o,two=t
  19. ring-type: cobwebby=c,evanescent=e,flaring=f,large=l, none=n,pendant=p,sheathing=s,zone=z
  20. spore-print-color: black=k,brown=n,buff=b,chocolate=h,green=r, orange=o,purple=u,white=w,yellow=y
  21. population: abundant=a,clustered=c,numerous=n, scattered=s,several=v,solitary=y
  22. habitat: grasses=g,leaves=l,meadows=m,paths=p, urban=u,waste=w,woods=d
  23. class:表示分类,p有毒,e没毒

1.1 将特征转为One-Hot编码

# 将值从字母转换为数字-onehot编码
mush_df_encoded = pd.get_dummies(mush_df)
mush_df_encoded.head()
class_e class_p cap-shape_b cap-shape_c cap-shape_f cap-shape_k cap-shape_s cap-shape_x cap-surface_f cap-surface_g ... population_s population_v population_y habitat_d habitat_g habitat_l habitat_m habitat_p habitat_u habitat_w
0 0 1 0 0 0 0 0 1 0 0 ... 1 0 0 0 0 0 0 0 1 0
1 1 0 0 0 0 0 0 1 0 0 ... 0 0 0 0 1 0 0 0 0 0
2 1 0 1 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 1 0 0 0
3 0 1 0 0 0 0 0 1 0 0 ... 1 0 0 0 0 0 0 0 1 0
4 1 0 0 0 0 0 0 1 0 0 ... 0 0 0 0 1 0 0 0 0 0

5 rows × 119 columns

1.2 分离特征数据与标签数据

# 将特征和类别标签分布赋值给 X 和 y
X_mush = mush_df_encoded.iloc[:,2:]
y_mush = mush_df_encoded.iloc[:,1]  #0表示没毒,1表示有毒

2. 训练SVM模型

建立pipeline训练管道

from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
#  先进行特征降维,然后再建立模型
pca = PCA(n_components=0.9, whiten=True, random_state=42)  # 保证降维后的数据保持90%的信息
svc = SVC(kernel='linear', class_weight='balanced')
model = make_pipeline(pca, svc)

将数据分为训练和测试数据

from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, ytest = train_test_split(X_mush, y_mush,random_state=41)   

调参:通过交叉验证寻找最佳的 C (控制间隔的大小)

from sklearn.model_selection import GridSearchCV
param_grid = {'svc__C': [1, 5, 10, 50]}
grid = GridSearchCV(model, param_grid)
%time grid.fit(Xtrain, ytrain)
print(grid.best_params_)
Wall time: 11.3 s
{'svc__C': 50}

使用训练好的SVM做预测

model = grid.best_estimator_
yfit = model.predict(Xtest)

生成性能报告

from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, Xtest, yfit, cv=5)
print(scores.mean())
0.9965517241379309
from sklearn.metrics import classification_report
print(classification_report(ytest, yfit,
                            target_names=['p','e']))
precision    recall  f1-score   support
           p       1.00      1.00      1.00      1047
           e       1.00      0.99      1.00       984
    accuracy                           1.00      2031
   macro avg       1.00      1.00      1.00      2031
weighted avg       1.00      1.00      1.00      2031
from sklearn.metrics import confusion_matrix
mat = confusion_matrix(ytest, yfit)
sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False,
            xticklabels=['p','e'],
            yticklabels=['p','e'])
plt.xlabel('true label')
plt.ylabel('predicted label')
Text(113.9222222222222, 0.5, 'predicted label')


相关文章
|
1天前
|
机器学习/深度学习 算法 网络安全
机器学习在网络安全威胁检测与防御中有广泛的应用
机器学习在网络安全威胁检测与防御中有广泛的应用
7 1
|
3天前
|
机器学习/深度学习 数据采集 搜索推荐
机器学习多场景实战(一)
机器学习已广泛应用,从个性化推荐到金融风控,数据指标是评估其效果的关键。数据指标包括活跃用户(DAU, MAU, WAU)衡量用户粘性,新增用户量和注册转化率评估营销效果,留存率(次日、7日、30日)反映用户吸引力,行为指标如PV(页面浏览量)、UV(独立访客)和转化率分析用户行为。产品数据指标如GMV、ARPU、ARPPU和付费率关注业务变现,推广付费指标(CPM, CPC, CPA等)则关乎广告效率。找到北极星指标,如月销售额或用户留存,可指导业务发展。案例中涉及电商销售数据,计算月销售金额、环比、销量、新用户占比、激活率和留存率以评估业务表现。
|
3天前
|
机器学习/深度学习 搜索推荐 数据挖掘
机器学习多场景实战(二 )
这是一个关于机器学习应用于电商平台用户行为分析的概要,包括以下几个关键点: 1. **月活跃用户分析**:通过购买记录确定活跃用户,计算每月活跃用户数。 2. **月客单价**:定义为月度总销售额除以月活跃用户数,衡量平均每位活跃用户的消费金额。 3. **新用户占比**:基于用户首次购买和最近购买时间判断新老用户,计算每月新用户的购买比例。 4. **激活率计算**:定义为当月与上月都有购买行为的用户数占上月购买用户数的比例,反映用户留存情况。 5. **Pandas数据操作**:使用Pandas库进行数据集合并(concat和merge),以及计算不同维度的组合。
|
6天前
|
机器学习/深度学习 数据采集 安全
【机器学习】安全领域:突破威胁检测的边界
【机器学习】安全领域:突破威胁检测的边界
13 1
|
6天前
|
机器学习/深度学习 人工智能 Java
【Sping Boot与机器学习融合:构建赋能AI的微服务应用实战】
【Sping Boot与机器学习融合:构建赋能AI的微服务应用实战】
10 1
|
12天前
|
机器学习/深度学习 搜索推荐 算法
【阿旭机器学习实战】【37】电影推荐系统---基于矩阵分解
【阿旭机器学习实战】【37】电影推荐系统---基于矩阵分解
|
12天前
|
机器学习/深度学习 数据可视化 算法
【阿旭机器学习实战】【36】糖尿病预测---决策树建模及其可视化
【阿旭机器学习实战】【36】糖尿病预测---决策树建模及其可视化
|
2天前
|
机器学习/深度学习 人工智能 算法
【昆虫识别系统】图像识别Python+卷积神经网络算法+人工智能+深度学习+机器学习+TensorFlow+ResNet50
昆虫识别系统,使用Python作为主要开发语言。通过TensorFlow搭建ResNet50卷积神经网络算法(CNN)模型。通过对10种常见的昆虫图片数据集('蜜蜂', '甲虫', '蝴蝶', '蝉', '蜻蜓', '蚱蜢', '蛾', '蝎子', '蜗牛', '蜘蛛')进行训练,得到一个识别精度较高的H5格式模型文件,然后使用Django搭建Web网页端可视化操作界面,实现用户上传一张昆虫图片识别其名称。
45 7
【昆虫识别系统】图像识别Python+卷积神经网络算法+人工智能+深度学习+机器学习+TensorFlow+ResNet50
|
3天前
|
机器学习/深度学习 人工智能 算法
算法金 | 统计学的回归和机器学习中的回归有什么差别?
**摘要:** 统计学回归重在解释,使用线性模型分析小数据集,强调假设检验与解释性。机器学习回归目标预测,处理大数据集,模型复杂多样,关注泛化能力和预测误差。两者在假设、模型、数据量和评估标准上有显著差异,分别适用于解释性研究和预测任务。
27 8
算法金 | 统计学的回归和机器学习中的回归有什么差别?
|
4天前
|
机器学习/深度学习 人工智能 Dart
AI - 机器学习GBDT算法
梯度提升决策树(Gradient Boosting Decision Tree),是一种集成学习的算法,它通过构建多个决策树来逐步修正之前模型的错误,从而提升模型整体的预测性能。