質問するログイン新規登録

質問編集履歴

1

時系列データに対するk近傍法のソースコードの追記

2020/11/09 05:18

投稿

AI_engineer
AI_engineer

スコア16

title CHANGED
File without changes
body CHANGED
@@ -18,4 +18,94 @@
18
18
  長文失礼いたします。
19
19
 
20
20
  ### 補足情報(FW/ツールのバージョンなど)
21
- Pythonを使って実装しています。
21
+ Pythonを使って実装しています。
22
+
23
+ ```python
24
+ import pandas as pd
25
+ import numpy as np
26
+ import matplotlib.pyplot as plt
27
+ from sklearn.neighbors import NearestNeighbors
28
+
29
+
30
+ '''
31
+ dataをsize毎のスライス窓に分割
32
+ '''
33
+
34
+ def main():
35
+ df = pd.read_csv("20191121.csv")
36
+
37
+ # 余分なデータをDataFrameから削除
38
+ df = df.drop(['name', 'x_rad/s', 'y_rad/s', 'z_rad/s'], axis=1)
39
+
40
+ df = df.set_index('time')
41
+
42
+ #x, y, z軸加速度を視認化
43
+ df.plot().legend(loc='upper left')
44
+
45
+ # 前から2480件のx軸加速度を学習データ、その次の2479件をテストデータとする
46
+ # # df.iloc[2479] ---> 53845130
47
+ # df.iloc[2480] ---> 53845150
48
+ train_data = df.loc[:53845130, 'x_ags']
49
+ test_data = df.loc[53845150:, 'x_ags'].reset_index(drop=True)
50
+
51
+ # 窓幅
52
+ width = 30
53
+
54
+ # k近傍法のk
55
+ nk = 1
56
+
57
+ # 窓幅を使ってベクトルの集合を作成
58
+ train = embed(train_data, width)
59
+ test = embed(test_data, width)
60
+
61
+ # k近傍法でクラスタリング
62
+ neigh = NearestNeighbors(n_neighbors=nk)
63
+ neigh.fit(train)
64
+
65
+ # 距離を計算
66
+ d = neigh.kneighbors(test)[0]
67
+
68
+ # 距離の正規化
69
+ mx = np.max(d)
70
+ d = d / mx
71
+
72
+ # 訓練データ
73
+ plt.subplot(221)
74
+ plt.plot(train_data, label='Training')
75
+ plt.xlabel("Amplitude", fontsize=12)
76
+ plt.ylabel("Sample", fontsize=12)
77
+ plt.grid()
78
+ leg = plt.legend(loc=1, fontsize=15)
79
+ leg.get_frame().set_alpha(1)
80
+
81
+ # 異常度
82
+ plt.subplot(222)
83
+ plt.plot(d, label='d')
84
+ plt.xlabel("Amplitude", fontsize=12)
85
+ plt.ylabel("Sample", fontsize=12)
86
+ plt.grid()
87
+ leg = plt.legend(loc=1, fontsize=15)
88
+ leg.get_frame().set_alpha(1)
89
+
90
+ # 検証用データ
91
+ plt.subplot(223)
92
+ plt.plot(test_data, label='Test')
93
+ plt.xlabel("Amplitude", fontsize=12)
94
+ plt.ylabel("Sample", fontsize=12)
95
+ plt.grid()
96
+ leg = plt.legend(loc=1, fontsize=15)
97
+ leg.get_frame().set_alpha(1)
98
+
99
+
100
+ def embed(lst, dim):
101
+ emb = np.empty((0, dim), float)
102
+ for i in range(lst.size - dim + 1):
103
+ tmp = np.array(lst[i:i+dim])[::-1].reshape((1, -1))
104
+ emb = np.append(emb, tmp, axis=0)
105
+ return emb
106
+
107
+ if __name__ == '__main__':
108
+ main()
109
+ ```
110
+
111
+ ![左上:訓練データ,左下:テストデータ,右上:異常度](15d9983fb3b40aded89010e0bc082414.png)