日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

将一维数据(序列)转化为二维数据(图像)的方法汇总GAFS, MTF, Recurrence plot,STFT

發布時間:2023/12/20 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 将一维数据(序列)转化为二维数据(图像)的方法汇总GAFS, MTF, Recurrence plot,STFT 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

將一維序列數據轉化為二維圖像數據的方法匯總 詳細 全面

  • 一、背景
  • 二、方法介紹
    • 格拉米角場 GAFs
      • 原理
      • 實現步驟
      • 調用示例
    • 馬爾可夫變遷場 MTF
      • 原理
      • 實現步驟
      • 調用示例
    • 遞歸圖 Recurrence Plot
      • 原理
      • 調用示例
    • 短時傅里葉變換 STFT
    • 原理
    • 實現步驟
    • 調用示例
  • References
  • 總結

一、背景

雖然深度學習方法(1D CNN, RNN, LSTM 等)可以直接處理一維數據,但是當前的深度學習方法主要還是處理二維結構數據的,特別是在計算機視覺CV以及自然語言處理NLP領域,各種各樣的方法層出不窮。因此,如果能夠將一維序列數據轉化為二維(圖像)數據, 則可以直接結合CV以及NLP領域的方法,是不是很有趣!

二、方法介紹

格拉米角場 GAFs

原理

縮放后的1D序列數據從直角坐標系統轉換到極坐標系統,然后通過考慮不同點之間的角度和/差以識別不同時間點的時間相關性。取決于是做角度和還是角度差,有兩種實現方法:GASF(對應做角度和), GADF(對應做角度差)。

實現步驟

Step 1:縮放,將數據范圍縮放到[-1,1]或者[0, 1], 公式如下:

Step 2: 將縮放后的序列數據轉換到極坐標系統,即將數值看作夾角余弦值,時間戳看作半徑,公式如下:

: 若數據縮放范圍為[-1, 1],則轉換后的角度范圍為[0, π pi π];若縮放范圍為[0, 1],則轉換后的角度范圍為[0, π pi π/2]。
Step 3:

可以看到,最終GASF和GADF的計算轉化到直角坐標系下變成了“類似”內積的操作。

效率問題:對于長度為n的序列數據,轉換后的GAFs尺寸為[n, n]的矩陣,可以采用PAA(分段聚合近似)先將序列長度減小,然后在轉換。 所謂的PAA就是:將序列分段,然后通過平均將每個段內的子序列壓縮為一個數值, 簡單吧!

調用示例

Python工具包pytl中已經提供了API,另外,筆者自行實現代碼, 想要查看實現細節以及獲取更多測試用例,可從我的 鏈接獲取。

''' EnvironmentPython 3.6, pyts: 0.11.0, Pandas: 1.0.3 ''' from mpl_toolkits.axes_grid1 import make_axes_locatable from pyts.datasets import load_gunpoint from pyts.image import GramianAngularField # call API X, _, _, _ = load_gunpoint(return_X_y=True) gasf = GramianAngularField(method='summation') X_gasf = gasf.transform(X) gadf = GramianAngularField(method='difference') X_gadf = gadf.transform(X)plt.figure() plt.suptitle('gunpoint_index_' + str(0)) ax1 = plt.subplot(121) ax1.plot(np.arange(len(rescale(X[k][:]))), rescale(X[k][:])) plt.title('rescaled time series') ax2 = plt.subplot(122, polar=True) r = np.array(range(1, len(X[k]) + 1)) / 150 theta = np.arccos(np.array(rescale(X[k][:]))) * 2 * np.pi # radian -> Angleax2.plot(theta, r, color='r', linewidth=3) plt.title('polar system') plt.show()plt.figure() plt.suptitle('gunpoint_index_' + str(0)) ax1 = plt.subplot(121) plt.imshow(X_gasf[k]) plt.title('GASF') divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.2) # Create an axes at the given *position*=right with the same height (or width) of the main axes plt.colorbar(cax=cax)ax2 = plt.subplot(122) plt.imshow(X_gadf[k]) plt.title('GASF') divider = make_axes_locatable(ax2) cax = divider.append_axes("right", size="5%",pad=0.2) # Create an axes at the given *position*=right with the same height (or width) of the main axes plt.colorbar(cax=cax) plt.show()

結果如下圖所示
縮放后的序列數據以及在極坐標系統的表示:

轉換后的GASF和GADF:


馬爾可夫變遷場 MTF

原理

基于1階馬爾可夫鏈,由于馬爾科夫轉移矩陣對序列的時間依賴并不敏感,因此作者考慮了時間位置關系提出了所謂的MTF。

實現步驟

Step 1: 首先將序列數據(長度為n)按照其取值范圍劃分為Q個bins (類似于分位數), 每個數據點 i 屬于一個唯一的qi ( ∈ in ∈ {1,2, …, Q}).
Step 2: 構建馬爾科夫轉移矩陣W,矩陣尺寸為:[Q, Q], 其中W[i,j]由qi中的數據被qj中的數據緊鄰的頻率決定,其計算公式如下:
w i , j = ∑ x ∈ q i , y ∈ q j , x + 1 = y 1 / ∑ j = 1 Q w i , j w_{i,j}=sum_{ orall x in q_{i}, y in q_{j},x+1=y}1/sum_{j=1}^{Q}w_{i,j} wi,j=∑x∈qi,y∈qj,x+1=y1/∑j=1Qwi,j
Step 3:構建馬爾科夫變遷場M, 矩陣尺寸為:[n, n], M[i,j]的值為W[qi, qj]

效率問題:原因與GAFs類似,為了提高效率,設法減小M的尺寸,思路與PAA類似,將M網格化,然后每個網格中的子圖用其平均值替代。

調用示例

Python工具包pytl中已經提供了API,API接口參考:https://pyts.readthedocs.io/en/latest/generated/pyts.image.MarkovTransitionField.html。另外,筆者自行實現代碼, 想要查看實現細節以及獲取更多測試用例,可從我的 github 鏈接獲取。

''' EnvironmentPython 3.6, pyts: 0.11.0, Pandas: 1.0.3 ''' from mpl_toolkits.axes_grid1 import make_axes_locatable from pyts.datasets import load_gunpoint from pyts.image import MarkovTransitionField ## call API X, _, _, _ = load_gunpoint(return_X_y=True) mtf = MarkovTransitionField() fullimage = mtf.transform(X)# downscale MTF of the time series (without paa) through mean operation batch = int(len(X[0]) / s) patch = [] for p in range(s):for q in range(s):patch.append(np.mean(fullimage[0][p * batch:(p + 1) * batch, q * batch:(q + 1) * batch])) # reshape patchimage = np.array(patch).reshape(s, s)plt.figure() plt.suptitle('gunpoint_index_' + str(k)) ax1 = plt.subplot(121) plt.imshow(fullimage[k]) plt.title('full image') divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.2) plt.colorbar(cax=cax)ax2 = plt.subplot(122) plt.imshow(patchimage) plt.title('MTF with patch average') divider = make_axes_locatable(ax2) cax = divider.append_axes("right", size="5%", pad=0.2) plt.colorbar(cax=cax) plt.show()

結果如圖所示:


遞歸圖 Recurrence Plot

遞歸圖(recurrence plot,RP)是分析時間序列周期性、混沌性以及非平穩性的一個重要方法,用它可以揭示時間序列的內部結構,給出有關相似性、信息量和預測性的先驗知識,遞歸圖特別適合短時間序列數據,可以檢驗時間序列的平穩性、內在相似性。

原理

遞歸圖是表示從原始時間序列提取的軌跡之間的距離的圖像
給定時間序列數據: ( x 1 , … , x n ) (x_1, ldots, x_n) (x1,…,xn),提取到的軌跡為:
x i = ( x i , x i + τ , … , x i + ( m 1 ) τ ) , i ∈ { 1 , … , n ( m 1 ) τ } ec{x}_i = (x_i, x_{i + au}, ldots, x_{i + (m - 1) au}), quad orall i in {1, ldots, n - (m - 1) au } x i=(xi,xi+τ,…,xi+(m1)τ),i∈{1,…,n(m1)τ}
其中: m m m是軌跡的維數, τ au τ是時延。 遞歸圖R是軌跡之間的成對距離,計算如下:
R i , j = Θ ( ε ∥ x i x j ∥ ) , i , j ∈ { 1 , … , n ( m 1 ) τ } R_{i, j} = Theta(arepsilon - | ec{x}_i - ec{x}_j |), quad orall i,j in {1, ldots, n - (m - 1) au } Ri,j=Θ(ε∥x ix j∥),i,j∈{1,…,n(m1)τ}
其中, Θ Theta Θ為Heaviside函數,而 ε arepsilon ε 是閾值。

調用示例

''' EnvironmentPython 3.6, pyts: 0.11.0, Pandas: 1.0.3 ''' from mpl_toolkits.axes_grid1 import make_axes_locatable from pyts.datasets import load_gunpoint from pyts.image import RecurrencePlotX, _, _, _ = load_gunpoint(return_X_y=True) rp = RecurrencePlot(dimension=3, time_delay=3) X_new = rp.transform(X) rp2 = RecurrencePlot(dimension=3, time_delay=10) X_new2 = rp2.transform(X) plt.figure() plt.suptitle('gunpoint_index_0') ax1 = plt.subplot(121) plt.imshow(X_new[0]) plt.title('Recurrence plot, dimension=3, time_delay=3') divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.2) plt.colorbar(cax=cax)ax1 = plt.subplot(122) plt.imshow(X_new2[0]) plt.title('Recurrence plot, dimension=3, time_delay=10') divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.2) plt.colorbar(cax=cax) plt.show()

結果如圖:


短時傅里葉變換 STFT

STFT可看作一種量化非平穩信號的頻率和相位含量隨時間變化的方式。.

原理

通過添加窗函數(窗函數的長度是固定的),首先對時域信號加窗,通過滑動窗口的方式將原始時域信號分割為多個片段,然后對每一個片段進行FFT變換,從而得到信號的時頻譜(保留了時域信息)。

實現步驟

假設序列的長度為 T T T, τ au τ為窗口窗口長度, s s s為滑動步長,W表示窗函數, 則STFT可以計算為:

S T F T ( τ , s ) ( X ) [ m , k ] = ∑ t = 1 T X [ t ] W ( t s m ) e x p { j 2 π k / τ ( t s m ) } STFT^{( au,s)}(X)_{[m,k]}=sum_{t=1}^{T}X_{[t]} cdot W(t-sm)cdot exp{-j2pi k / au cdot (t-sm)} STFT(τ,s)(X)[m,k]=∑t=1TX[t]W(tsm)exp{j2πk/τ(tsm)}

變換后的STFT尺寸為:[M, K], M代表時間維度,K代表頻率幅值(復數形式),為方便起見,假設 s = τ s= au s=τ, 即窗口之間沒有重疊,則
M = T / τ M=T/ au M=T/τ,
K = τ K =lfloor au floor K=τ/2 + 1

注:相比于DFT, STFT在某種程度上幫助我們恢復時間分辨率,然而在可達到的時間分辨率和頻率之間會發生權衡,這就是所謂的不確定性原理。具體來說,窗口的寬度( τ au τ)越大,頻域分辨率就越高,相應地,時域分辨率越低;窗口的寬度( τ au τ)越小,頻域分辨率就越低,相應地,時域分辨率越高。

調用示例

python包 scipy提供STFT的API,具體官方文檔介紹見:https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.stft.html

scipy.signal.stft(x,fs = 1.0,window =‘hann’,nperseg = 256,noverlap = None,nfft = None,detrend = False,return_oneside = True,boundary
=‘zeros’,padded = True,axis = -1 )

參數解釋
x: 時域信號;
fs: 信號的采樣頻率;
window: 窗函數;
nperseg: 窗函數長度;
noverlap: 相鄰窗口的重疊長度,默認為50%;
nfft: FFT的長度,默認為nperseg。如大于nperseg會自動進行零填充;
return_oneside : True返回復數實部,None返回復數。
示例代碼:

""" @author: masterqkk, masterqkk@outlook.com Environment:python: 3.6Pandas: 1.0.3matplotlib: 3.2.1 """ import pickle import numpy as np import matplotlib.pyplot as plt import scipy.signal as scisig from mpl_toolkits.axes_grid1 import make_axes_locatable from pyts.datasets import load_gunpointif __name__ == '__main__':X, _, _, _ = load_gunpoint(return_X_y=True)fs = 10e3 # sampling frequencyN = 1e5 # 10 s 1signalamp = 2 * np.sqrt(2)time = np.arange(N) / float(fs)mod = 500 * np.cos(2 * np.pi * 0.25 * time)carrier = amp * np.sin(2 * np.pi * 3e3 * time + mod)noise_power = 0.01 * fs / 2noise = np.random.normal(loc=0.0, scale=np.sqrt(noise_power), size=time.shape)noise *= np.exp(-time / 5)x = carrier + noise # signal with noiseper_seg_length = 1000 # window lengthf, t, Zxx = scisig.stft(x, fs, nperseg=per_seg_length, noverlap=0, nfft=per_seg_length, padded=False)print('Zxx.shaope: {}'.format(Zxx.shape)) plt.figure()plt.suptitle('gunpoint_index_0')ax1 = plt.subplot(211)ax1.plot(x)plt.title('signal with noise')ax2 = plt.subplot(212)ax2.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp)plt.title('STFT Magnitude')ax2.set_ylabel('Frequency [Hz]')ax2.set_xlabel('Time [sec]')plt.show()

運行結果
得到STFT結果尺寸為:
Zxx.shaope: (501, 101), 頻率成分的數量為 1000 lfloor 1000 floor 1000/2 + 1 = 501, 窗口片段的長度為1e5/1000 + 1=101 (此處應該是進行了pad)

References

1.Imaging Time-Series to Improve Classification and Imputation
2.Encoding Time Series as Images for Visual Inspection and Classification Using Tiled Convolutional Neural Networks
3.J.-P Eckmann, S. Oliffson Kamphorst and D Ruelle, “Recurrence Plots of Dynamical Systems”. Europhysics Letters (1987)
4.Stoica, Petre, and Randolph Moses,Spectral Analysis of Signals, Prentice Hall, 2005
5.https://laszukdawid.com/tag/recurrence-plot/

總結

最后附上時間序列數據集下載鏈接:http://www.cs.ucr.edu/~eamonn/time_series_data/, 幾乎包含了所有當前該領域的數據集。
希望能幫助到大家, 未完待續。歡迎交流:masterqkk@outlook.com

總結

以上是生活随笔為你收集整理的将一维数据(序列)转化为二维数据(图像)的方法汇总GAFS, MTF, Recurrence plot,STFT的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。