提取渥太华大学机械故障敏感特征,再利用决策树分类(Python代码)

news2024/9/28 17:30:30

该数据集是从渥太华大学采集的轴承振动信号,这些信号是在时间变化的转速条件下收集的。数据集包含4个不同引擎的每个引擎的12秒信号数据。采样频率为10000

 代码主要流程:

  1. 数据导入与预处理:

    • 通过scipy.io.loadmat()函数从"dataset.mat"文件中加载数据集,其中包含了不同类别的时间序列数据。
    • 将不同类别的时间序列数据存储到df_normaldf_innerdf_rollerdf_outer四个数组中。
    • 将数据按照类别存储到data数组中,同时将类别名称存储到label数组中。
    • 定义类别标签映射的字典label_dic
  2. 数据划分与预测:

    • 定义了函数instancing_data()用于生成训练集和测试集。函数根据给定的train_sizesample_duration参数,将数据划分为训练集和测试集,并对每个实例应用自回归模型进行预测。
    • 调用instancing_data()函数,得到训练集df_train和测试集df_test
    • 从训练集中取出一些样本实例数据,分别命名为xtbxthxtd
    • 使用statsmodels.tsa.ar_model.AutoReg类创建并拟合自回归模型,对xtb数据进行预测得到xth_predxtd_pred
  3. 可视化:

    • 使用Matplotlib库绘制两个子图,分别展示预测的健康状态和损坏状态与真实值的对比。
  4. 自回归模型评估:

    • 创建自回归模型对象,并对样本数据xt进行不同滞后阶数的拟合,计算AIC值(Akaike information criterion)并绘制AIC值的变化趋势图。
    • 绘制样本数据的自相关图。
  5. 特征提取:

    • 定义了函数feature_extraction()用于特征提取。该函数对训练集中的每个实例应用自回归模型,并计算特定特征值gamma1gamma2
    • gamma1gamma2分别用于衡量每个实例的预测残差与整体残差的方差比例和模型参数的方差比例。
    • 通过特征提取得到了特征数据df_train_ex
  6. 特征可视化:

    • 绘制了特征gamma1gamma2的散点图,并按照类别进行着色。
  7. 决策树分类:

    • 使用sklearn.tree.DecisionTreeClassifier创建决策树分类器,并对特征数据进行拟合。
    • 使用Graphviz库绘制决策树图,并绘制分类区域图。
  8. 测试集分类:

    • 对测试集进行分类预测,并生成混淆矩阵。
  9. 不同样本持续时间下的分类评分:

    • 创建决策树分类器,并分别计算不同样本持续时间下的分类评分(F1 Score)。
    • 绘制样本持续时间和分类评分之间的关系图。

总体来说,这段代码涉及了时间序列数据的处理、特征提取、模型拟合、分类预测等步骤,并通过可视化展示了各个阶段的结果和评估指标。

 

 

 

 

 

 

 完整代码如下:

运行版本要求:

scipy version>=: 1.7.3
numpy version>=: 1.19.2
pandas version>=: 1.2.0
graphviz version>=: 0.16
seaborn version>=: 0.11.1
matplotlib version>=: 3.4.2

python>=3.6.0

import scipy
from scipy import io
import numpy as np
import pandas as pd 

import graphviz


import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['simhei'] # 添加中文字体为黑体
plt.rcParams['axes.unicode_minus'] =False
import matplotlib as mpl

from statsmodels.tsa.ar_model import AutoReg
from sklearn import tree
from sklearn.metrics import f1_score
from sklearn.tree import DecisionTreeClassifier as DTC

from mlxtend.plotting import plot_decision_regions, plot_confusion_matrix
from mlxtend.evaluate import confusion_matrix
custom_plot = {'font.serif':'Computer Modern Roman',
               'font.size': 18, 
               'text.usetex': False,
               'axes.grid.which': 'both',
               'axes.grid': True,
               'grid.linestyle': '--',
               'xtick.minor.visible':True,
               'ytick.minor.visible':True,
               'ytick.minor.size':4,
               'ytick.major.size':10,
               'lines.markersize': 10.0,
              }

mpl.rcParams.update(custom_plot)
file = "dataset.mat"
dataset = scipy.io.loadmat(file)

df_normal = dataset["normal"].reshape(-1)
df_inner = dataset["inner"].reshape(-1)
df_roller = dataset["roller"].reshape(-1)
df_outer = dataset["outer"].reshape(-1)

data = [df_normal,df_inner,df_roller,df_outer]
label = ['正常', '内圈故障', '滚子故障', '外圈故障']

label_dic = {0: '正常',
             1: '内圈故障',
             2: '滚子故障',
             3: '外圈故障'}

frequency = 10000
def instancing_data(train_size = 0.7, sample_duration = 0.2):
    
    df_test = pd.DataFrame(columns=('signal', 'label', 'instance'))
    df_train = df_test.copy()
    
    for j, arr in enumerate(data):
        
        size = arr.size
        samples = sample_duration * frequency
        n_instances = size / samples
        
        if n_instances > int(n_instances):
            n_instances += 1
        
        samples = int(samples)
        n_instances = int(n_instances)
        
        for i in range(n_instances):
            signal = arr[0+samples*i:samples*(i+1)]
            df_aux = pd.DataFrame({'signal': signal, 'label': j, 'instance': i + n_instances * j})
            
            if i < n_instances * train_size:
                
                df_train = df_train.append(df_aux, ignore_index = True)
            
            else:
                df_test = df_test.append(df_aux, ignore_index = True)
    
    return df_train, df_test
df_train, df_test = instancing_data()
xtb = df_train.loc[df_train['instance'] == 0, 'signal'].to_numpy()
xth = df_train.loc[df_train['instance'] == 10, 'signal'].to_numpy()
xtd = df_train.loc[df_train['instance'] == 153, 'signal'].to_numpy()

ar = 6

model = AutoReg(xtb, ar, old_names = False).fit()

params = model.params[1:]
bias = model.params[0]

xth_pred = np.sum([xth[k:xth.size-ar+k] * p for k, p in enumerate(params[::-1])], axis = 0) + bias
xtd_pred = np.sum([xtd[k:xtd.size-ar+k] * p for k, p in enumerate(params[::-1])], axis = 0) + bias

fig, ax = plt.subplots(1, 2, figsize= (18, 6))

ax[0].plot(xth, color = 'b', label = '健康状态')
ax[0].plot(xth_pred, label = '参考模型', color = 'g', alpha = 0.7);
ax[0].set_title(f'AR({ar}) 健康模型应用于健康状态')

ax[1].plot(xtd, color = 'r', label = '损伤状态')
ax[1].plot(xtd_pred, label = '参考模型', color = 'g', alpha = 0.7);
ax[1].set_title(f'AR({ar}) 健康模型应用于损伤状态')

ax[0].legend()
ax[1].legend()

ax[0].set_xlabel('信号')
ax[1].set_xlabel('信号')

fig.tight_layout()
xt = df_train.loc[df_train['instance'] == 0, 'signal']
AIC = []

for i in range(1, 30):
    model = AutoReg(xt.to_numpy(), i, old_names = False)
    res = model.fit()
    AIC.append(res.aic)

fig, ax = plt.subplots(1, 2, figsize=(24, 6))
ax[0].plot(AIC)
ax[0].set_xlabel('Lag')
ax[0].set_ylabel('AIC 分数')
ax[0].set_title('Akaike 信息准则')

pd.plotting.autocorrelation_plot(xt, ax=ax[1])
ax[1].set_title('自相关图');
def feature_extraction(df, xtb, ar = 11):
    
    er_model = AutoReg(xtb.to_numpy(), ar, old_names = False).fit()
    
    instances = df['instance'].unique()
    
    n_instances = instances.size
    
    var_er_pred = np.var(er_model.resid)
    var_er_coef = np.var(er_model.params)
    
    gamma1 = []
    gamma2 = []
    label = []
    
    for i in range(n_instances):
        xt = df.loc[df['instance'] == instances[i], 'signal']
        ei_model = AutoReg(xt.to_numpy(), ar, old_names = False).fit()
        
        params = er_model.params[1:]
        bias = er_model.params[0]
        xtp = np.sum([xt[k:xt.size-ar+k] * p for k, p in enumerate(params[::-1])], axis = 0) + bias
        
        var_ei_pred = np.var(xt[ar:]-xtp)
        var_ei_coef = np.var(ei_model.params)
        
        gamma1.append(var_ei_pred/var_er_pred)
        gamma2.append(var_ei_coef/var_er_coef)
        label.append(df.loc[df['instance'] == instances[i], 'label'].iat[0])
    
    df_result = pd.DataFrame({'instance': range(n_instances), 'g1': gamma1, 'g2': gamma2, 'label': label})
    
    return df_result
df_train_ex = feature_extraction(df_train, df_train.loc[df_train['instance'] == 0, 'signal'])
df_aux = df_train_ex.replace({'label': label_dic})

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
ax.set_title('由特征 $\gamma_1$ 和 $\gamma_2$ 组成的实例分布')
sns.scatterplot(data=df_aux, x='g1', y = 'g2', hue='label', ax=ax)
ax.set_xlabel('$\gamma_1$')
ax.set_ylabel('$\gamma_2$');

X_train = df_train_ex[['g1', 'g2']]
y_train = df_train_ex['label']
model = DTC(max_depth=2)
model.fit(X_train.to_numpy(), y_train)
dot_data = tree.export_graphviz(model, out_file=None, 
                                feature_names= ['Gamma 1', 'Gamma 2'],  
                                class_names=label,
                                label='root',
                                filled=True)

# Draw graph
graph = graphviz.Source(dot_data, format="png") 
graph
fig, ax = plt.subplots(1, 1, figsize=(12, 6))
ax.set_title('决策树分类区域')
plot_decision_regions(X_train.to_numpy(), y_train.to_numpy(), 
                      clf=model, markers = ('o', 's', '^', 'D'),
                      ax=ax,
                     )
ax.set_xlabel('$\gamma_1$')
ax.set_ylabel('$\gamma_2$')
L=ax.legend()
for i in range(4):
    L.get_texts()[i].set_text(label[i])
df_test_ex = feature_extraction(df_test, df_train.loc[df_train['instance'] == 0, 'signal'])
X_test = df_test_ex[['g1', 'g2']].to_numpy()
y_test = df_test_ex['label']

y_pred = model.predict(X_test)
mpl.rcParams.update({'axes.grid': False})

cm = confusion_matrix(y_test, y_pred)
fig, ax = plot_confusion_matrix(cm, figsize=(8, 8), class_names=label)
ax.set_title('测试混淆矩阵')
model = DTC(max_depth=2)

sample_durations = [0.2, 0.1, 0.05, 0.02, 0.01]

class_scores = []
binary_scores = []

for sd in sample_durations:
    df_train, df_test = instancing_data(sample_duration = sd)
    
    df_train_ex = feature_extraction(df_train, df_train.loc[df_train['instance'] == 0, 'signal'])
    X_train = df_train_ex[['g1', 'g2']].to_numpy()
    y_train = df_train_ex['label']
    
    df_test_ex = feature_extraction(df_test, df_train.loc[df_train['instance'] == 0, 'signal'])
    X_test = df_test_ex[['g1', 'g2']].to_numpy()
    y_test = df_test_ex['label']
    
    model.fit(X_train, y_train)
    
    y_pred = model.predict(X_test)
    
    y_test_bin = y_test.copy()
    y_pred_bin = y_pred.copy()
    
    y_test_bin[y_test_bin > 0] = 1
    y_pred_bin[y_pred_bin > 0] = 1
    
    
    f1 = f1_score(y_test, y_pred, average = 'macro')
    f1_bin = f1_score(y_test_bin, y_pred_bin)
    
    class_scores.append(f1)
    binary_scores.append(f1_bin)
    print(f'样本持续时间: {sd}\n状态分类得分: {f1:.2f}\n健康状况分类得分: {f1_bin:.2f}\n')
mpl.rcParams.update({'axes.grid': True})

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
ax.plot(sample_durations, class_scores, ls = '-', marker = 'o', color='b', label = '状态分类')
ax.plot(sample_durations, binary_scores, ls = '--', marker = 'o', color='r', label = '健康状况分类')
ax.set_xlabel('样本持续时间 [s]')
ax.set_ylabel('F1 分数')
ax.set_title('F1 分数与样本持续时间')
ax.legend();

 若对数据集和代码放在一起的压缩包感兴趣可以关注下面最后一行:
 

import scipy
from scipy import io
import numpy as np
import pandas as pd 

import graphviz


import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['simhei'] # 添加中文字体为黑体
plt.rcParams['axes.unicode_minus'] =False
import matplotlib as mpl

from statsmodels.tsa.ar_model import AutoReg
from sklearn import tree
from sklearn.metrics import f1_score
from sklearn.tree import DecisionTreeClassifier as DTC

from mlxtend.plotting import plot_decision_regions, plot_confusion_matrix
from mlxtend.evaluate import confusion_matrix
#代码和数据集放在一起的压缩包:https://mbd.pub/o/bread/ZJyUlZxp

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/808671.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

docker配置文件挂载(容器数据管理)

目录 数据卷&#xff08;容器数据管理&#xff09;什么是数据卷数据集操作命令创建和查看数据卷挂载数据卷案例案例-给nginx挂载数据卷案例-给MySQL挂载本地目录 总结 数据卷&#xff08;容器数据管理&#xff09; 在之前的nginx案例中&#xff0c;修改nginx的html页面时&#…

教雅川学缠论05-线段

线段需要满足下面4个条件&#xff1a; 1.是由3条笔&#xff0c;或者3条以上组成&#xff0c;同笔一样&#xff0c;线段也是有方向的 2.如果线段起始于向上笔&#xff0c;则终止与向上笔&#xff08;一定不会终止与向下笔&#xff09; 3.如果线段起始于向下笔&#xff0c;则终止…

Python接口自动化测试框架运行原理及流程

这篇文章主要介绍了Python接口自动化测试框架运行原理及流程,文中通过示例代码介绍的非常详细&#xff0c;对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 本文总结分享介绍接口测试框架开发&#xff0c;环境使用python3selenium3unittestddtrequests测试框…

Themis 国库建设计划启动,开启去中心化新征程

在未来的金融领域&#xff0c;去中心化金融&#xff08;DeFi&#xff09;正在成为一种重要的趋势。在这股DeFi热潮中&#xff0c;作为Filecoin 生态下的一颗璀璨明珠&#xff0c;Themis 上线仅2个月&#xff0c;多项数据便稳居Filecoin-FVM榜首&#xff0c;TVL更是牢牢处于File…

wxWidgets 打开文件对话框wxFileDialog

wxFileDialog dialog(this, _("Open file"), wxEmptyString, wxEmptyString); if (dialog.ShowModal() wxID_OK) { wxString strPath dialog.GetPath(); } 效果图&#xff1a;

小莫计数摸高训练器:让孩子健康成长的好帮手

现在孩子们的生活方式越来越单一&#xff0c;很多孩子缺乏运动&#xff0c;喜欢在手机上看视频、玩游戏&#xff0c;导致身体素质下降。为了让孩子更好地锻炼身体&#xff0c;我最近入手了一款小莫计数摸高训练器&#xff0c;这是个很实用的儿童锻炼辅助器。 小莫计数摸高训练器…

【JAVASE】循环结构

⭐ 作者&#xff1a;小胡_不糊涂 &#x1f331; 作者主页&#xff1a;小胡_不糊涂的个人主页 &#x1f4c0; 收录专栏&#xff1a;浅谈Java &#x1f496; 持续更文&#xff0c;关注博主少走弯路&#xff0c;谢谢大家支持 &#x1f496; 循环 1. 循环结构1.1 while 循环1.2 bre…

无涯教程-jQuery - Scale方法函数

Scale 效果可以与show/hide/toggle一起使用。这会使元素缩小或增长一个百分比因子。 Scale - 语法 selector.hide|show|toggle( "scale", {arguments}, speed ); 这是所有参数的描述- direction - 方向。可以是"both"&#xff0c;"垂…

【UE5】快速认识入门

目录 &#x1f31f;1. 快速安装&#x1f31f;2. 简单快捷键操作&#x1f31f;3. 切换默认的打开场景&#x1f31f;4. 虚幻引擎术语 &#x1f31f;1. 快速安装 进入Unreal Engine 5官网进行下载即可&#xff1a;UE5 &#x1f4dd;官方帮助文档 打开后在启动器里创建5.2.1引擎…

Optitrack下飞控刷px4固件并进行参数配置(视觉vision定位适用)

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一:寻找固件二&#xff1a;QGC配置参数2.1&#xff1a;飞控初始化配置2.2&#xff1a;利用视觉定位作为位置反馈 三&#xff1a;PID调试/飞行日志查看 前言 参…

WIZnet W6100-EVB-Pico DHCP 配置教程(三)

前言 在上一章节中我们讲了网络信息配置&#xff0c;那些网络信息的配置都是用户手动的去配置的&#xff0c;为了能跟电脑处于同一网段&#xff0c;且电脑能成功ping通板子&#xff0c;我们不仅要注意子网掩码&#xff0c;对于IP地址主机位和网络位的划分&#xff0c;而且还要注…

级联选择框

文章目录 实现级联选择框效果图实现前端工具版本添加依赖main.js导入依赖级联选择框样式 后端数据库设计 实现级联选择框 效果图 实现 前端 工具版本 node.js v16.6.0vue3 级联选择框使用 Element-Plus 实现 添加依赖 在 package.json 添加依赖&#xff0c;并 npm i 导入…

【RTT驱动框架分析01】-pin/gpio驱动分析

0gpio使用测试 LED测试 #define LED1_PIN GET_PIN(C, 1) void led1_thread_entry(void* parameter) {rt_pin_mode(LED1_PIN, PIN_MODE_OUTPUT);while(1){rt_thread_delay(50); //delay 500msrt_pin_write(LED1_PIN, PIN_HIGH);rt_thread_delay(50); //delay 50…

漏洞发现-操作系统之漏洞探针类型利用修复(42)

主要包括四个部分&#xff0c; 系统漏洞发现的的意义&#xff1a;应用是基于操作系统的&#xff0c;针对的操作系统&#xff0c;如果漏洞本身就有问题&#xff0c;就不需要对特定的网站特定的漏洞寻找&#xff0c;因为网站是寄生在服务器上&#xff0c;而服务器丢失就可以帮助…

Sentinel dashboard的使用;Nacos保存Sentinel限流规则

Sentinel dashboard的使用 往期文章 Nacos环境搭建Nacos注册中心的使用Nacos配置中心的使用Sentinel 容灾中心的使用 参考文档 Sentinel alibaba/spring-cloud-alibaba Wiki GitHub 限流结果 下载sentinel-dashboard github地址&#xff1a;Sentinel/sentinel-dashboar…

【雕爷学编程】MicroPython动手做(13)——掌控板之RGB三色灯3

知识点&#xff1a;什么是掌控板&#xff1f; 掌控板是一块普及STEAM创客教育、人工智能教育、机器人编程教育的开源智能硬件。它集成ESP-32高性能双核芯片&#xff0c;支持WiFi和蓝牙双模通信&#xff0c;可作为物联网节点&#xff0c;实现物联网应用。同时掌控板上集成了OLED…

TypeScript基础篇 - TS模块

目录 模块的概念 Export 语法&#xff08;default&#xff09; Export 语法&#xff08;non-default&#xff09; import 别名 Type Export语法【TS】 模块相关配置项&#xff1a;module【tsconfig.json】 模块相关配置项&#xff1a;moduleResolution 小节总结 模块的…

手写vuex

vuex 基本用法 vuex是作为插件使用&#xff0c;Vue.use(vuex) 最后注册给new Vue的是一个new Vuex.Store实例 // store.js import Vue from vue import Vuex from vuexVue.use(Vuex) // Vue.use注册插件 // new Vuex.Store实例 export default new Vuex.Store({state: {},gette…

详解Mybatis之逆向工程问题

编译软件&#xff1a;IntelliJ IDEA 2019.2.4 x64 操作系统&#xff1a;win10 x64 位 家庭版 Maven版本&#xff1a;apache-maven-3.6.3 Mybatis版本&#xff1a;3.5.6 文章目录 一. Mybatis中的逆向工程是什么&#xff1f;二. 什么是MBG&#xff1f;三. MBG如何使用&#xff1…

Android Studio 启用设备远程调试配置完整步聚

启用手机设置->开发者选项-无线调试,然后选择允许 已启用后无线调试变成绿色 ,点击无线调试进入详情页面 点击Android Studio的Device Manager 下的WIFI图标 会弹出下图窗口 打开手机的开发者选项中的WIFI调试(无线调试)下的使用二维码配对设备进行扫描. 设备配对成功后手机…