当前位置: 首页 > news >正文

基于卷积神经网络故障诊断模型的 t-SNE特征可视化

基于卷积神经网络故障诊断模型的 t-SNE特征可视化

  • 1. t-sne可视化基本概念
  • 2. sklearn.manifold.TSNE函数的参数说明
  • 3. 基于tensorflow2卷积网络t-SNE特征可视化
  • 参考

1. t-sne可视化基本概念

  1. 流形学习的设计目的
    Manifold learning is an approach to non-linear dimensionality reduction. Algorithms for this task are based on the idea that the dimensionality of many data sets is only artificially high.
    Manifold是一种非线性降维的方法。这个任务的算法是基于这样一种想法,即许多数据集的维数只是人为地偏高。
    Manifold Learning can be thought of as an attempt to generalize linear frameworks like PCA to be sensitive to non-linear structure in data. Though supervised variants exist, the typical manifold learning problem is unsupervised: it learns the high-dimensional structure of the data from the data itself, without the use of predetermined classifications.
    Manifold可以被认为是一种推广线性框架的尝试,如PCA,以敏感的非线性数据结构。虽然有监督变量存在,但典型的Manifold问题是非监督的:它从数据本身学习数据的高维结构,而不使用预定的分类。
  2. 数据降维与可视化
    t-distributed Stochastic Neighbor Embedding(t-SNE),即t-分布随机邻居嵌入。t-SNE是一个可视化高维数据的工具。它将数据点之间的相似性转化为联合概率,并试图最小化低维嵌入和高维数据联合概率之间的Kullback-Leibler差异。t-SNE有一个非凸的代价函数,即通过不同的初始化,我们可以得到不同的结果。强烈建议使用另一种降维方法(如密集数据的PCA或稀疏数据的集群svd)来减少维数到一个合理的数量(如50),如果特征的数量非常高。这将抑制一些噪声,加快样本间成对距离的计算。
  3. 主要特点以及功能作用–判别数据是否可分
    t-SNE是目前来说效果最好的数据降维与可视化方法,但是它的缺点也很明显,比如:占内存大,运行时间长。但是,当我们想要对高维数据进行分类,又不清楚这个数据集有没有很好的可分性(即同类之间间隔小,异类之间间隔大),可以通过t-SNE投影到2维或者3维的空间中观察一下。如果在低维空间中具有可分性,则数据是可分的;如果在高维空间中不具有可分性,可能是数据不可分,也可能仅仅是因为不能投影到低维空间。t-SNE(TSNE)的原理是将数据点之间的相似度转换为概率。原始空间中的相似度由高斯联合概率表示,嵌入空间的相似度由“学生t分布”表示。

2. sklearn.manifold.TSNE函数的参数说明

参数

  • n_componentsint, default=2: 嵌入空间的尺寸。
  • min_grad_normfloat, default=1e-7:如果梯度范数低于这个阈值,优化将停止。
  • init{‘random’, ‘pca’} or ndarray of shape (n_samples, n_components), default=’random’:初始化的嵌入。可能的选项是’ random ‘,’ pca '和numpy数组的形状(n_samples, n_components)。PCA初始化不能与预先计算的距离一起使用,而且通常比随机初始化更全局稳定。

3. 基于tensorflow2卷积网络t-SNE特征可视化

import numpy as np
import pandas as pd

from sklearn.model_selection import cross_val_score, train_test_split, KFold
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import LabelEncoder
import itertools
import tensorflow
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.layers import Dense, Activation, Flatten, Convolution1D, Dropout, MaxPooling1D, BatchNormalization
from tensorflow.keras.models import model_from_json
from tensorflow.keras.utils import plot_model
from tensorflow.python.keras.utils import np_utils
from tensorflow.keras.models import Sequential
from sklearn.manifold import TSNE

"""
一维卷积神经网络 输入为信号片段;输出为轴承的故障类别;
做的t-sne可视化demo程序
点靠颜色和形状区分 x o
"""

# 载入数据
df = pd.read_csv(r'C:\Users\86139\PycharmProjects\pythonProject_at_tsinghua\TF2_t_SNE\14改.csv')
#####################################################################
# 定义神经网络
def baseline_model():
    model = Sequential()
    model.add(Convolution1D(16, 128, strides=1, input_shape=(1024, 1), padding="same"))
    model.add(Activation('tanh'))
    model.add(MaxPooling1D(2, strides=2, padding='same'))

    # model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None))
    model.add(Convolution1D(32, 3, padding='same'))
    model.add(
        BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros',
                           gamma_initializer='ones', moving_mean_initializer='zeros',
                           moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None,
                           beta_constraint=None, gamma_constraint=None))
    model.add(Activation('tanh'))
    model.add(MaxPooling1D(2, strides=2, padding='same'))

    model.add(Flatten())
    model.add(Dropout(0.3))
    model.add(Dense(60, activation='tanh'))
    model.add(Dense(2, activation='softmax'))
    print(model.summary())
    sgd = SGD(lr=0.01, nesterov=True, decay=1e-6, momentum=0.9)
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

# 模型训练
nb_epoch = 10
model = baseline_model()
estimator = model.fit(X_train, Y_train, epochs=nb_epoch, validation_data=(X_test, Y_test), batch_size=32)
num_layer=1
layer = tensorflow.keras.backend.function([model.layers[0].input], [model.layers[num_layer].output])

f1 = layer([X_train])[0]
np.set_printoptions(threshold=np.inf)
print(f"f1-shape: {f1.shape}")
# print(f1)
f2 = f1.reshape(f1.shape[0]*f1.shape[2], f1.shape[1])
# print(f2)
num = f1.shape[-1]
print(num)

def get_data(f1):
    # digits = datasets.load_digits(n_class=10)
    digits = 2
    data = f2  # digits.data		# 图片特征
    label = K  # digits.target		# 图片标签
    n_samples = f1.shape[0] * f1.shape[2]
    n_features = f1.shape[1]  # data.shape		# 数据集的形状
    return data, label, n_samples, n_features

data, label, n_samples, n_features = get_data(f1)  # 调用函数,获取数据集信息
print('Starting compute t-SNE Embedding...')
ts = TSNE(n_components=2, init='pca', random_state=0)

# t-SNE降维
result = ts.fit_transform(data)

# 数据归一化与可视化
x_min, x_max = np.min(result, 0), np.max(result, 0)
data = (result - x_min) / (x_max - x_min)  # 对数据进行归一化处理
#####################################################################
# 把标签读出来--因为就是增倍,且序号顺序未变
label2 = np.repeat(label, 16)
map_marker = {0.0: 'o', 1.0: 'x'}
markers = list(map(lambda x: map_marker[x], label2))
map_color = {0.0: 'b', 1.0: 'g'}
colors = list(map(lambda x: map_color[x], label2))

mscatter(data[:, 0], data[:, 1], s=20, c=colors, cmap='tab10', m=markers, alpha=0.3)
plt.legend()
plt.show()

可视化部分参考了下这篇博客[2]
在这里插入图片描述

参考

[1] https://blog.csdn.net/m0_47410750/article/details/123119544?spm=1001.2014.3001.5502
[2] https://blog.csdn.net/u014571489/article/details/102667570

相关文章:

  • 不写DAX实现TopN和其他
  • ArrayList实现简易扑克牌
  • 程序员薪资有多高?8大互联网大厂纷纷开奖,校招真的杀疯了|最值得投递的大厂|应届生必看
  • 集成学习详解
  • 微信小程序开发入门与实战(组件的使用)
  • 【Linux篇】第十篇——基础IO(系统文件IO+文件描述符+重定向+文件系统+软硬链接)
  • java计算机毕业设计食品点评及售卖系统源代码+数据库+系统+lw文档
  • 一起Talk Android吧(第三百八十七回:LiveData)
  • 整理了几个100%会踩的Python细节坑,提前防止脑血栓
  • 计算机视觉 神经网络,神经网络模型可视化
  • day011--mysql中的不可逆加密函数,信息函数及转换函数
  • 基于java厨艺交流平台计算机毕业设计源码+系统+lw文档+mysql数据库+调试部署
  • TinyKv Project3 PartA Multi-raft KV
  • 交换机与路由技术-27-OSPF路由重分发
  • throw和throws的区别
  • 【知识碎片】第三方登录弹窗效果
  • axios请求、和返回数据拦截,统一请求报错提示_012
  • JavaScript中的对象个人分享
  • Java多线程(4):使用线程池执行定时任务
  • Map集合、散列表、红黑树介绍
  • PAT A1017 优先队列
  • 从零开始学习部署
  • 动手做个聊天室,前端工程师百无聊赖的人生
  • 翻译--Thinking in React
  • 关于使用markdown的方法(引自CSDN教程)
  • 技术胖1-4季视频复习— (看视频笔记)
  • 讲清楚之javascript作用域
  • 码农张的Bug人生 - 见面之礼
  • 配置 PM2 实现代码自动发布
  • 入职第二天:使用koa搭建node server是种怎样的体验
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • 正则表达式-基础知识Review
  • ​MySQL主从复制一致性检测
  • #、%和$符号在OGNL表达式中经常出现
  • #《AI中文版》V3 第 1 章 概述
  • #Linux(帮助手册)
  • #宝哥教你#查看jquery绑定的事件函数
  • #使用清华镜像源 安装/更新 指定版本tensorflow
  • (4)Elastix图像配准:3D图像
  • (51单片机)第五章-A/D和D/A工作原理-A/D
  • (备忘)Java Map 遍历
  • (蓝桥杯每日一题)love
  • (四)linux文件内容查看
  • . Flume面试题
  • .Net6 Api Swagger配置
  • .NET序列化 serializable,反序列化
  • .NET中winform传递参数至Url并获得返回值或文件
  • ??eclipse的安装配置问题!??
  • @property python知乎_Python3基础之:property
  • @RequestMapping处理请求异常
  • [20150629]简单的加密连接.txt
  • [2016.7.Test1] T1 三进制异或
  • [2021ICPC济南 L] Strange Series (Bell 数 多项式exp)
  • [ABP实战开源项目]---ABP实时服务-通知系统.发布模式
  • [ACM] hdu 1201 18岁生日