专注于工业智能预警系统研发, 通过机理算法和数据驱动算法分析振动信号、音频、DCS、PLC信号、SCADA信号等设备运行状态数据对机器设备进行看病预诊,为机器设备健康运行保驾护航。 网站正在不断建设和完善过程中,欢迎大家给予建议和参与社区建设
52phm,专注于预测性维护知识学习和交流,欢迎广大从事预测性维护行业人员投稿,投稿请联系管理员(wx: www52phmcn),投稿内容可以是:
python 编码规范主要有以下5个方面: 代码布局——导入——表达式和语句中的空格——注释——命名约定
上下左右总体的布局
(1)缩进:4个空格一个缩进层次,通常在if语句、for语句和while语句等等后面,一个【Tab】键等于4个空格。
(2)行的最大长度:一般每行不超过80字符。
(3)空行:用两行空行分割顶层函数和类的定义;类内方法的定义用单个空行分割;当空行用于分割方法(method)的定义时,在'class'行和第一个方法定义之间也要有一个空行.
(1)单独的行中导入(Imports):一行只能有一个模块,例如:
# 错误
import sys, os
# 正确
import sys
import os
(2)从一个模块中导入多个子模块(多个子函数):
from sklearn import metrics, datasets
(3)把模块重新自定义为新的名字:是为了简化模块名
例如:将可视化模块matplotlib.pyplot重命名为plt,以后调用就使用plt,使用起来方便
import matplotlib.pyplot as plt
(1)在逗号,分号或冒号后,应该空一格如:
# 错误:
if x == 4 :print(x ,y);x ,y = y ,x
# 要修改成:
if x == 4: print(x, y); x, y = y, x
(2)要紧挨着圆括号,方括号和花括号的,如:
# 错误:
spam( ham[ 1 ], { eggs: 2 } )
# 要修改成:
spam(ham[1], {eggs: 2})
(3)要紧贴在索引或切片(slicing?下标?)开始的开式括号前,如:
# 错误:
dict ['key'] = list [index]
# 要修改成:
dict['key'] = list[index]
(4)在赋值(或其它)运算符周围的用于和其它并排的一个以上的空格,如:
# 错误:
x=1
y=2
long_variable=3
# 正确:
x = 1
y = 2
long_variable = 3
(5)始终在这些二元运算符两边放置一个空格:赋值(=), 比较(==, <, >, !=,<>, <=, >=, in, not in, is, is not), 布尔运算 (and, or, not).
# Yes:
i = i 1
submitted = 1
x = x * 2 - 1
hypot2 = x * x y * y
c = (a b) * (a – b)
# No:
i=i1
submitted =1
x = x*2 - 1
hypot2 = x*x y*y
c = (ab) * (a-b)
(6)不要在用于指定关键字参数或默认参数值的'='号周围使用空格,例如:
# 正确
def complex(real, imag=0.0):
return magic(r=real, i=imag)
# 错误
def complex(real, imag = 0.0):
return magic(r = real, i = imag)
(7)不要将多条语句写在同一行上.
# 正确:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
# 错误:
if foo == 'blah':
do_blah_thing()do_one(); do_two(); do_three()
单行和多行注释 (1)行内注释:一个行内注释是和语句在同一行的注释.行内注释应该谨慎适用.行内注释应该至少用两个空格和语句分开. 它们应该以'#'和单个空格开始.
# 网站地址(单独一行注释:#一个空格注释内容)
__website__ = "htpp://www.52phm.cn" # 网站地址(和代码在同一行注释:两个空格#一个空格注释内容)
(2)多行注释:注释块通常应用于跟随着一些(或者全部)代码并和这些代码有着相同的缩进层次. 注释块中每行以'#'和一个空格开始(除非他是注释内的缩进文本). 注释块内的段落以仅含单个'#'的行分割. 注释块上下方最好有一空行包围(或上方两行下方一行,对一个新函数定义段的注释)
# 网站地址(单独一行注释:#一个空格注释内容)
# 网站地址
# 网站地址
__website__ = "htpp://www.52phm.cn"
"""
简介:
52phm社区,工业互联网人的技术交流社区
"""
name = "52phm社区,工业互联网人的技术交流社区"
(1)模块名:模块应该是不含下划线的,简短的,小写的名字.例如:
re/time/pymysql/os
(2)类名:几乎没有例外,类名总是使用首字母大写单词串(CapWords)的约定。例如:
MyCat
WeChat
(3)异常名:如果模块对所有情况定义了单个异常,它通常被叫做"error"或"Error". 似乎内建(扩展)的模块使用"error"(例如:os.error), 而 Python 模块通常用"Error" (例如: xdrlib.Error).
(4)函数名:函数名应该为小写,可能用下划线风格单词以增加可读性. mixedCase 仅被允许用于这种风格已经占优势的上下文(如: threading.py) 以便保持向后兼容.
(5)方法名和实例变量:这段大体上和函数相同:通常使用小写单词,必要时用下划线分隔增加可读性;使用一个前导下划线仅用于不打算作为类的公共接口的内部方法和实例变量;使用两个前导下划线以表示类私有的名字.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Spectral feature extraction"""
import numpy as np
import scipy
import scipy.signal
import scipy.fftpack
from .. import util
from .. import filters
from ..util.exceptions import ParameterError
from ..util.decorators import deprecate_positional_args
from ..core.convert import fft_frequencies
from ..core.audio import zero_crossings
from ..core.spectrum import power_to_db, _spectrogram
from ..core.constantq import cqt, hybrid_cqt
from ..core.pitch import estimate_tuning
__all__ = [
"spectral_centroid",
"spectral_bandwidth",
"spectral_contrast",
"spectral_rolloff",
"spectral_flatness",
"poly_features",
"rms",
"zero_crossing_rate",
"chroma_stft",
"chroma_cqt",
"chroma_cens",
"melspectrogram",
"mfcc",
"tonnetz",
]
# -- Spectral features -- #
@deprecate_positional_args
def spectral_centroid(
*,
y=None,
sr=22050,
S=None,
n_fft=2048,
hop_length=512,
freq=None,
win_length=None,
window="hann",
center=True,
pad_mode="constant",
):
"""Compute the spectral centroid.
Each frame of a magnitude spectrogram is normalized and treated as a
distribution over frequency bins, from which the mean (centroid) is
extracted per frame.
More precisely, the centroid at frame ``t`` is defined as [#]_::
centroid[t] = sum_k S[k, t] * freq[k] / (sum_j S[j, t])
where ``S`` is a magnitude spectrogram, and ``freq`` is the array of
frequencies (e.g., FFT frequencies in Hz) of the rows of ``S``.
.. [#] Klapuri, A., & Davy, M. (Eds.). (2007). Signal processing
methods for music transcription, chapter 5.
Springer Science & Business Media.
Parameters
----------
y : np.ndarray [shape=(..., n,)] or None
audio time series. Multi-channel is supported.
sr : number > 0 [scalar]
audio sampling rate of ``y``
S : np.ndarray [shape=(..., d, t)] or None
(optional) spectrogram magnitude
n_fft : int > 0 [scalar]
FFT window size
hop_length : int > 0 [scalar]
hop length for STFT. See `librosa.stft` for details.
freq : None or np.ndarray [shape=(d,) or shape=(d, t)]
Center frequencies for spectrogram bins.
If `None`, then FFT bin center frequencies are used.
Otherwise, it can be a single array of ``d`` center frequencies,
or a matrix of center frequencies as constructed by
`librosa.reassigned_spectrogram`
win_length : int <= n_fft [scalar]
Each frame of audio is windowed by `window()`.
The window will be of length ``win_length`` and then padded
with zeros to match ``n_fft``.
If unspecified, defaults to ``win_length = n_fft``.
window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
- a window specification (string, tuple, or number);
see `scipy.signal.get_window`
- a window function, such as `scipy.signal.windows.hann`
- a vector or array of length ``n_fft``
.. see also:: `librosa.filters.get_window`
center : boolean
- If `True`, the signal ``y`` is padded so that frame
`t` is centered at ``y[t * hop_length]``.
- If `False`, then frame ``t`` begins at ``y[t * hop_length]``
pad_mode : string
If ``center=True``, the padding mode to use at the edges of the signal.
By default, STFT uses zero padding.
Returns
-------
centroid : np.ndarray [shape=(..., 1, t)]
centroid frequencies
See Also
--------
librosa.stft : Short-time Fourier Transform
librosa.reassigned_spectrogram : Time-frequency reassigned spectrogram
Examples
--------
From time-series input:
>>> y, sr = librosa.load(librosa.ex('trumpet'))
>>> cent = librosa.feature.spectral_centroid(y=y, sr=sr)
>>> cent
array([[1768.888, 1921.774, ..., 5663.477, 5813.683]])
From spectrogram input:
>>> S, phase = librosa.magphase(librosa.stft(y=y))
>>> librosa.feature.spectral_centroid(S=S)
array([[1768.888, 1921.774, ..., 5663.477, 5813.683]])
Using variable bin center frequencies:
>>> freqs, times, D = librosa.reassigned_spectrogram(y, fill_nan=True)
>>> librosa.feature.spectral_centroid(S=np.abs(D), freq=freqs)
array([[1768.838, 1921.801, ..., 5663.513, 5813.747]])
Plot the result
>>> import matplotlib.pyplot as plt
>>> times = librosa.times_like(cent)
>>> fig, ax = plt.subplots()
>>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
... y_axis='log', x_axis='time', ax=ax)
>>> ax.plot(times, cent.T, label='Spectral centroid', color='w')
>>> ax.legend(loc='upper right')
>>> ax.set(title='log Power spectrogram')
"""
# input is time domain:y or spectrogam:s
#
S, n_fft = _spectrogram(
y=y,
S=S,
n_fft=n_fft,
hop_length=hop_length,
win_length=win_length,
window=window,
center=center,
pad_mode=pad_mode,
)
if not np.isrealobj(S):
raise ParameterError(
"Spectral centroid is only defined " "with real-valued input"
)
elif np.any(S < 0):
raise ParameterError(
"Spectral centroid is only defined " "with non-negative energies"
)
# Compute the center frequencies of each bin
if freq is None:
freq = fft_frequencies(sr=sr, n_fft=n_fft)
if freq.ndim == 1:
# reshape for broadcasting
freq = util.expand_to(freq, ndim=S.ndim, axes=-2)
# Column-normalize S
return np.sum(freq * util.normalize(S, norm=1, axis=-2), axis=-2, keepdims=True)
@deprecate_positional_args
def zero_crossing_rate(y, *, frame_length=2048, hop_length=512, center=True, **kwargs):
"""Compute the zero-crossing rate of an audio time series.
Parameters
----------
y : np.ndarray [shape=(..., n)]
Audio time series. Multi-channel is supported.
frame_length : int > 0
Length of the frame over which to compute zero crossing rates
hop_length : int > 0
Number of samples to advance for each frame
center : bool
If `True`, frames are centered by padding the edges of ``y``.
This is similar to the padding in `librosa.stft`,
but uses edge-value copies instead of zero-padding.
**kwargs : additional keyword arguments
See `librosa.zero_crossings`
.. note:: By default, the ``pad`` parameter is set to `False`, which
differs from the default specified by
`librosa.zero_crossings`.
Returns
-------
zcr : np.ndarray [shape=(..., 1, t)]
``zcr[..., 0, i]`` is the fraction of zero crossings in frame ``i``
See Also
--------
librosa.zero_crossings : Compute zero-crossings in a time-series
Examples
--------
>>> y, sr = librosa.load(librosa.ex('trumpet'))
>>> librosa.feature.zero_crossing_rate(y)
array([[0.044, 0.074, ..., 0.488, 0.355]])
"""
# check if audio is valid
util.valid_audio(y, mono=False)
if center:
padding = [(0, 0) for _ in range(y.ndim)]
padding[-1] = (int(frame_length // 2), int(frame_length // 2))
y = np.pad(y, padding, mode="edge")
y_framed = util.frame(y, frame_length=frame_length, hop_length=hop_length)
kwargs["axis"] = -2
kwargs.setdefault("pad", False)
crossings = zero_crossings(y_framed, **kwargs)
return np.mean(crossings, axis=-2, keepdims=True)
2022-01-17 23:15:26
博客笔记
813
分类:算法开发
专栏:python基础
2022-01-17 23:36:20
博客笔记
772
分类:算法开发
专栏:python基础
2022-01-17 23:54:38
博客笔记
831
分类:算法开发
专栏:python基础
关注公众号进群
让志同道合读者学习交流
通过python编程语言实现特征工程功能,本篇特征工程文章较为全面的介绍数据预处理,缺失值处理方法、异常值处理方法、数据无量纲、标准化、归一化,另外还介绍特征选择、特征降维等特征工程知识
2021-12-04 12:12:30
博客笔记
4525
分类:算法开发
专栏:特征工程
1、频谱泄露 对于频率为fs的正弦序列,它的频谱应该只是在fs处有离散谱。但是,在利用DFT求它的频谱时,对时域做了截断,结果使信号的频谱不只是在fs处有离散谱,而是在以fs为中心的频带范围内都有谱线出现,它们可以理解为是从fs频率上“泄漏”出去的,这种现象称 为频谱“泄漏”。2、代码分析如果我们波形不能在fft_size个取样中形成整数个周期的话会怎样呢?将上篇博客中的采样对象...
2021-12-14 14:06:09
互联网
782
分类:算法开发
专栏:数字信号处理
首先我们来安装python1、首先进入网站下载:点击打开链接(或自己输入网址https://www.python.org/downloads/),进入之后如下图,选择图中红色圈中区域进行下载。2、下载完成后如下图所示3、双击exe文件进行安装,如下图,并按照圈中区域进行设置,切记要勾选打钩的框,然后再点击Customize install
2021-12-15 20:40:08
互联网
807
分类:开发环境
专栏:下载安装
新安装了Linux系统(CentOS 6),发现已安装的python版本是2.6. 在网上搜索研究之后总结了一下怎么在保留python2的同时安装最新版的python3。1. 查看 Python 的版本号:命令行输入以下命令就可以查看python版本:#python -V 或# python --version2. 下载3.x新版本可以访问python的官方网站查看最新的python版本以及下载...
2021-12-16 17:35:07
互联网
884
分类:开发环境
专栏:下载安装
1、python介绍Python由荷兰数学和计算机科学研究学会的吉多·范罗苏姆 于1990 年代初设计,作为一门叫做ABC语言的替代品。Python提供了高效的高级数据结构,还能简单有效地面向对象编程。Python语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本和快速开发应用的编程语言, 随着版本的不断更新和语言新功能的添加,逐渐被用于独立的、大型项目的开发。
2022-01-16 11:22:32
博客笔记
1005
分类:算法开发
专栏:python基础
window环境下运行新建一个hello.py文件# -*- coding: utf-8 -*-print("Hello, World!")如果安装了pycharm或者其它编辑器,那么可以直接运行hello world程序
2022-01-17 22:21:56
博客笔记
486
分类:算法开发
专栏:python基础
python内置关键字python内置关键字是指变量、常量、函数、属性、类、模块标识符,比如def表示函数标识符,if表示条件语句标识符等。下面列出python常见的关键字:1、获取关键字import keywordprint(keyword.kwlist)""" 输出['False', 'None', 'True', 'and', 'as','assert','break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except
2022-01-17 23:48:03
博客笔记
764
分类:算法开发
专栏:python基础
python模块import导入模块导入分为python内置模块(或者第三方模块)导入和自定义模块导入。模块导入方法可以总结为5大导入方法,下面以python内置模块角度来举例介绍5大导入方法。(1)import… 方法表示导入某个模块# 导入numpy模块import numpyarr = numpy.array([1, 2, 4])print(arr)# [1 2 4](2)import…as…方法import xx as yy,意思是把xx作为yy表示,相当于xx可以使用yy来
2022-01-17 23:59:41
博客笔记
1256
分类:算法开发
专栏:python基础
python数据类型python编程语言中有6个标准的数据类型,如下:String(字符串)Number(数字)Tuple(元组)List(列表)Dictionary(字典)Set(集合)其中,python的6大数据类型中,又可以分为可变数据和不可变数据,具体如下:可变数据类型:列表、字典、集合不可变数据类型:字符串、数字、元组如何理解可变、不可变数据类型呢?小知解答:可变是指在初始化相应数据之后,仍然可以编辑;不可变是指初始化相应数据之后,不可以再次编辑下面分别对各个
2022-01-19 13:19:38
博客笔记
886
分类:算法开发
专栏:python基础
1. 当运用计算机实现工程测试信号处理时,不可能对无限长的信号进行测量和运算,而是取其有限的时间片段进行分析。做法是从信号中截取一个时间片段,然后用观察的信号时间片段进行周期延拓处理,得到虚拟的无限长的信号,然后就可以对信号进行傅里叶变换、相关分析等数学处理。无线长的信号被截断以后,其频谱发生了畸变,原来集中在f(0)处的能量被分散到两个较宽的频带中去了(这种现象称之为频谱能量泄漏)。 1. 为了减少频谱能量泄漏,可采用不同的截取函数对信号进行截断,截断函数称为窗函数,简称为窗。 1. 信号截断以后产生的能量泄漏现象是必然的,因为窗函数w(t)是一个频带无限的函数,所以即使原信号x(t)是限带宽信号,而在截断以后也必然成为无限带宽的函数,即信号在频域的能量与分布被扩展了。又从采样定理可知,无论采样频率多高,只要信号一经截断,就不可避免地引起混叠,因此信号截断必然导致一些误差。泄漏与窗函数频谱的两侧旁瓣有关,如果两侧瓣的高度趋于零,而使能量相对集中在主瓣,就可以较为接近于真实的频谱,为此,在时间域中可采用不同的窗函数来截断信号。
2022-02-11 13:19:32
博客笔记
905
分类:算法开发
专栏:振动信号预处理
从事设备故障预测与健康管理行业多年的PHM算法工程师(机器医生)、国际振动分析师, 实践、研发和交付的项目涉及“化工、工业机器人、风电机组、钢铁、核电、机床、机器视觉”等领域。专注于工业智能预警系统研发, 通过机理算法和数据驱动算法分析振动信号、音频、DCS、PLC信号、SCADA信号等设备运行状态数据对机器设备进行看病预诊,为机器设备健康运行保驾护航。