Yinxing commited on
Commit
b29b43f
·
verified ·
1 Parent(s): 47d9934

Upload MEDIAデータ補完.ipynb

Browse files
Files changed (1) hide show
  1. MEDIAデータ補完.ipynb +461 -0
MEDIAデータ補完.ipynb ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "id": "UK8TSMbvp3zZ"
8
+ },
9
+ "outputs": [],
10
+ "source": [
11
+ "path = r'D:\\Github\\階層化多変量BASSモデル\\bog_cats_data_all.xlsx'"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {
18
+ "id": "l678Xe5Np3zb",
19
+ "outputId": "4663089e-c45e-45b0-df44-72d22dedcc35"
20
+ },
21
+ "outputs": [
22
+ {
23
+ "data": {
24
+ "text/plain": [
25
+ "tensor([[0., 1., 0., 0., 0.],\n",
26
+ " [0., 1., 0., 0., 0.],\n",
27
+ " [0., 1., 0., 0., 0.],\n",
28
+ " [0., 1., 0., 0., 0.],\n",
29
+ " [0., 1., 0., 0., 0.],\n",
30
+ " [0., 1., 0., 0., 0.],\n",
31
+ " [0., 0., 0., 0., 0.],\n",
32
+ " [0., 0., 0., 0., 0.],\n",
33
+ " [0., 0., 0., 0., 0.],\n",
34
+ " [0., 0., 0., 0., 0.],\n",
35
+ " [0., 0., 0., 0., 0.],\n",
36
+ " [0., 0., 0., 0., 0.],\n",
37
+ " [1., 0., 0., 0., 0.],\n",
38
+ " [1., 0., 0., 0., 0.],\n",
39
+ " [1., 0., 0., 0., 0.],\n",
40
+ " [1., 0., 0., 0., 0.],\n",
41
+ " [1., 0., 0., 0., 0.],\n",
42
+ " [1., 0., 0., 0., 0.],\n",
43
+ " [0., 0., 0., 0., 0.],\n",
44
+ " [0., 0., 0., 0., 0.],\n",
45
+ " [0., 0., 0., 0., 0.],\n",
46
+ " [0., 0., 0., 0., 0.],\n",
47
+ " [0., 0., 0., 0., 0.],\n",
48
+ " [0., 0., 0., 0., 0.],\n",
49
+ " [0., 0., 0., 1., 0.],\n",
50
+ " [0., 0., 0., 1., 0.],\n",
51
+ " [0., 0., 0., 1., 0.],\n",
52
+ " [0., 0., 0., 1., 0.],\n",
53
+ " [0., 0., 0., 1., 0.],\n",
54
+ " [0., 0., 0., 1., 0.]])"
55
+ ]
56
+ },
57
+ "execution_count": 684,
58
+ "metadata": {},
59
+ "output_type": "execute_result"
60
+ }
61
+ ],
62
+ "source": [
63
+ "import pandas as pd\n",
64
+ "df = pd.read_excel(path, sheet_name='std')\n",
65
+ "\n",
66
+ "detect_columns = ['Ninchi', 'Kyoumi','TVshow', 'Gekijoyokoku']\n",
67
+ "cols = []\n",
68
+ "\n",
69
+ "for col in df.columns:\n",
70
+ " for detect_col in detect_columns:\n",
71
+ " if detect_col in col:\n",
72
+ " cols.append(col)\n",
73
+ "\n",
74
+ "col_d = torch.zeros(len(cols), 5)\n",
75
+ "\n",
76
+ "# dummies\n",
77
+ "for i, col in enumerate(cols):\n",
78
+ " if 'IyokuOverNinchi'in col:\n",
79
+ " col_d[i, 0] = 1\n",
80
+ " elif 'Ninchi' in col:\n",
81
+ " col_d[i, 1] = 1\n",
82
+ " elif 'Kyomi' in col:\n",
83
+ " col_d[i, 2] = 1\n",
84
+ " elif 'TVshow' in col:\n",
85
+ " col_d[i, 3] = 1\n",
86
+ "col_d\n",
87
+ ""
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": null,
93
+ "metadata": {
94
+ "id": "nu9l0fPtp3zb"
95
+ },
96
+ "outputs": [],
97
+ "source": [
98
+ "import torch"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": null,
104
+ "metadata": {
105
+ "id": "mNNXxXN1p3zb",
106
+ "outputId": "56bf5a96-16f8-4184-ea8c-7dedb21bbe69"
107
+ },
108
+ "outputs": [
109
+ {
110
+ "data": {
111
+ "text/plain": [
112
+ "torch.Size([268, 6, 7])"
113
+ ]
114
+ },
115
+ "execution_count": 685,
116
+ "metadata": {},
117
+ "output_type": "execute_result"
118
+ }
119
+ ],
120
+ "source": [
121
+ "import torch\n",
122
+ "time_lag = 6\n",
123
+ "\n",
124
+ "# create a time-lagged dataset (batch, time_lag, features)\n",
125
+ "def create_time_lagged_data(x, time_lag, val=2, col_d=None):\n",
126
+ " # fill nan with 0 for start part\n",
127
+ " x = pd.Series(x).fillna(0).values\n",
128
+ " start = 0\n",
129
+ " for start in range(len(x)):\n",
130
+ " if x[start] != 0:\n",
131
+ " break\n",
132
+ " for stops in range(len(x), 0, -1):\n",
133
+ " if x[stops-1] != 0:\n",
134
+ " break\n",
135
+ " x = x[start:stops]\n",
136
+ "\n",
137
+ " data = torch.zeros(len(x)-time_lag, time_lag, 2+len(col_d))\n",
138
+ " # [0, 0, 1]をデータ毎にrepeat\n",
139
+ " col_d = torch.cat([col_d.repeat(i+1, 1) for i in range(len(x))])\n",
140
+ " for i in range(len(x)-time_lag):\n",
141
+ " data[i,:,0] = torch.tensor(x[i:i+time_lag]) * 10\n",
142
+ " # 公開時期\n",
143
+ " data[i,:,1] = torch.tensor(range(i, i+time_lag))\n",
144
+ " data[i,:,2:] = col_d[i:i+time_lag]\n",
145
+ " train_d = data[:-val]\n",
146
+ " val_d = data[-val:]\n",
147
+ " return train_d, val_d\n",
148
+ "\n",
149
+ "dfs = []\n",
150
+ "val_dfs = []\n",
151
+ "for col,col_type in zip(cols,col_d):\n",
152
+ " d = create_time_lagged_data(df[col].values, time_lag, col_d=col_type)\n",
153
+ " dfs.append(d[0])\n",
154
+ " val_dfs.append(d[1])\n",
155
+ "\n",
156
+ "dfs_t = torch.cat(dfs, dim=0)\n",
157
+ "val_dfs_t = torch.cat(val_dfs, dim=0)\n",
158
+ "dfs_t.shape"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "execution_count": null,
164
+ "metadata": {
165
+ "id": "2eJUTqJWp3zc"
166
+ },
167
+ "outputs": [],
168
+ "source": [
169
+ "# LSTM\n",
170
+ "import torch.nn as nn\n",
171
+ "from torch.functional import F\n",
172
+ "# relu\n",
173
+ "\n",
174
+ "\n",
175
+ "class LSTM(nn.Module):\n",
176
+ " def __init__(self, input_size, hidden_size, num_layers, output_size):\n",
177
+ " super(LSTM, self).__init__()\n",
178
+ " self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)\n",
179
+ " self.fc = nn.Linear(hidden_size, hidden_size)\n",
180
+ " self.output = nn.Linear(hidden_size, output_size)\n",
181
+ " #self.norm = nn.BatchNorm1d(hidden_size)\n",
182
+ " self.layer_norm = nn.LayerNorm(hidden_size)\n",
183
+ "\n",
184
+ "\n",
185
+ " def forward(self, x):\n",
186
+ " out, _ = self.lstm(x, None)\n",
187
+ " out = self.layer_norm(F.relu(self.fc(out[:, -1, :])))\n",
188
+ " out = self.output(out)\n",
189
+ " return out"
190
+ ]
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "execution_count": null,
195
+ "metadata": {
196
+ "id": "oItavj7kp3zc"
197
+ },
198
+ "outputs": [],
199
+ "source": [
200
+ "# dataloader\n",
201
+ "from torch.utils.data import DataLoader, TensorDataset\n",
202
+ "\n",
203
+ "train_loader = DataLoader(TensorDataset(dfs_t), batch_size=8, shuffle=True)"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "code",
208
+ "execution_count": null,
209
+ "metadata": {
210
+ "id": "McVizErzp3zc",
211
+ "outputId": "50cf1b19-ccdf-4459-cb20-ca77f36f3d74"
212
+ },
213
+ "outputs": [
214
+ {
215
+ "name": "stdout",
216
+ "output_type": "stream",
217
+ "text": [
218
+ "epoch 0, loss 11.606//test loss 6.443\n",
219
+ "epoch 5, loss 2.083//test loss 1.252\n",
220
+ "epoch 10, loss 1.142//test loss 0.802\n",
221
+ "epoch 15, loss 0.985//test loss 0.738\n",
222
+ "epoch 20, loss 0.891//test loss 0.706\n",
223
+ "epoch 25, loss 0.857//test loss 0.627\n",
224
+ "epoch 30, loss 0.875//test loss 0.813\n",
225
+ "epoch 35, loss 0.758//test loss 0.595\n",
226
+ "epoch 40, loss 0.729//test loss 0.686\n",
227
+ "epoch 45, loss 0.705//test loss 0.618\n",
228
+ "epoch 50, loss 0.835//test loss 0.595\n",
229
+ "epoch 55, loss 0.524//test loss 0.600\n",
230
+ "epoch 60, loss 0.494//test loss 0.848\n",
231
+ "epoch 65, loss 0.665//test loss 0.630\n",
232
+ "epoch 70, loss 0.532//test loss 0.801\n",
233
+ "epoch 75, loss 0.421//test loss 0.697\n",
234
+ "epoch 80, loss 0.433//test loss 0.747\n",
235
+ "epoch 85, loss 0.401//test loss 0.723\n",
236
+ "epoch 90, loss 0.437//test loss 0.902\n",
237
+ "epoch 95, loss 0.433//test loss 0.869\n",
238
+ "epoch 100, loss 0.324//test loss 0.799\n",
239
+ "epoch 105, loss 0.326//test loss 0.624\n",
240
+ "epoch 110, loss 0.343//test loss 0.735\n",
241
+ "epoch 115, loss 0.499//test loss 0.845\n",
242
+ "epoch 120, loss 0.317//test loss 0.823\n",
243
+ "epoch 125, loss 0.591//test loss 0.787\n",
244
+ "epoch 130, loss 0.281//test loss 0.693\n",
245
+ "epoch 135, loss 0.395//test loss 0.824\n",
246
+ "epoch 140, loss 0.289//test loss 0.809\n",
247
+ "epoch 145, loss 0.250//test loss 0.653\n",
248
+ "epoch 150, loss 0.261//test loss 0.863\n",
249
+ "epoch 155, loss 0.265//test loss 0.782\n",
250
+ "epoch 160, loss 0.253//test loss 0.799\n",
251
+ "epoch 165, loss 0.251//test loss 0.564\n",
252
+ "epoch 170, loss 0.248//test loss 0.793\n",
253
+ "epoch 175, loss 0.519//test loss 0.867\n",
254
+ "epoch 180, loss 0.242//test loss 0.719\n",
255
+ "epoch 185, loss 0.248//test loss 0.789\n",
256
+ "epoch 190, loss 0.229//test loss 0.773\n",
257
+ "epoch 195, loss 0.245//test loss 0.688\n",
258
+ "epoch 200, loss 0.257//test loss 0.709\n",
259
+ "epoch 205, loss 0.384//test loss 0.828\n",
260
+ "epoch 210, loss 0.212//test loss 0.593\n",
261
+ "epoch 215, loss 0.223//test loss 0.660\n",
262
+ "epoch 220, loss 0.194//test loss 0.558\n",
263
+ "epoch 225, loss 0.200//test loss 0.860\n",
264
+ "epoch 230, loss 0.180//test loss 0.837\n",
265
+ "epoch 235, loss 0.220//test loss 0.599\n",
266
+ "epoch 240, loss 0.219//test loss 0.977\n",
267
+ "epoch 245, loss 0.174//test loss 0.603\n",
268
+ "epoch 250, loss 0.154//test loss 0.729\n",
269
+ "epoch 255, loss 0.162//test loss 0.642\n",
270
+ "epoch 260, loss 0.167//test loss 0.569\n",
271
+ "epoch 265, loss 0.162//test loss 0.569\n",
272
+ "epoch 270, loss 0.130//test loss 0.674\n",
273
+ "epoch 275, loss 0.150//test loss 0.581\n",
274
+ "epoch 280, loss 0.352//test loss 0.722\n",
275
+ "epoch 285, loss 0.224//test loss 0.801\n",
276
+ "epoch 290, loss 0.211//test loss 0.707\n",
277
+ "epoch 295, loss 0.150//test loss 0.692\n",
278
+ "epoch 300, loss 0.125//test loss 0.603\n",
279
+ "epoch 305, loss 0.121//test loss 0.614\n",
280
+ "epoch 310, loss 0.117//test loss 0.594\n",
281
+ "epoch 315, loss 0.116//test loss 0.680\n",
282
+ "epoch 320, loss 0.121//test loss 0.643\n",
283
+ "epoch 325, loss 0.134//test loss 0.644\n",
284
+ "epoch 330, loss 0.183//test loss 0.763\n",
285
+ "Best Epoch: 44\n"
286
+ ]
287
+ },
288
+ {
289
+ "data": {
290
+ "text/plain": [
291
+ "<All keys matched successfully>"
292
+ ]
293
+ },
294
+ "execution_count": 688,
295
+ "metadata": {},
296
+ "output_type": "execute_result"
297
+ }
298
+ ],
299
+ "source": [
300
+ "# Training\n",
301
+ "import torch.optim as optim\n",
302
+ "\n",
303
+ "input_size = dfs_t.shape[2]\n",
304
+ "hidden_size = 64\n",
305
+ "num_layers = 1\n",
306
+ "output_size = 1\n",
307
+ "num_epochs = 331\n",
308
+ "learning_rate = 5e-4\n",
309
+ "\n",
310
+ "# seed\n",
311
+ "torch.manual_seed(0)\n",
312
+ "torch.cuda.manual_seed(0)\n",
313
+ "\n",
314
+ "model = LSTM(input_size, hidden_size, num_layers, output_size)\n",
315
+ "criterion = nn.MSELoss()\n",
316
+ "optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n",
317
+ "\n",
318
+ "rmses = []\n",
319
+ "for epoch in range(num_epochs):\n",
320
+ " total_loss = 0\n",
321
+ " model.train()\n",
322
+ " for t in train_loader:\n",
323
+ " x = t[0][:,:-1,:]\n",
324
+ " y = t[0][:,-1,:1]\n",
325
+ " #print(f'x: {x}, y: {y}')\n",
326
+ " outputs = model(x)\n",
327
+ " optimizer.zero_grad()\n",
328
+ " loss = criterion(outputs, y)\n",
329
+ " loss.backward()\n",
330
+ " optimizer.step()\n",
331
+ " total_loss += loss.item()\n",
332
+ "\n",
333
+ " if epoch % 5 == 0:\n",
334
+ " print('epoch {}, loss {:.3f}'.format(epoch, total_loss / len(train_loader)), end='//')\n",
335
+ "\n",
336
+ " # test\n",
337
+ " model.eval()\n",
338
+ " x = val_dfs_t[:, :-1, :]\n",
339
+ " y = val_dfs_t[:, -1, :1]\n",
340
+ " outputs = model(x)\n",
341
+ " loss = criterion(outputs, y)\n",
342
+ " rmses.append(loss.item())\n",
343
+ " if loss.item() == min(rmses):\n",
344
+ " torch.save(model.state_dict(), 'best.pth')\n",
345
+ "\n",
346
+ "\n",
347
+ "\n",
348
+ "\n",
349
+ " print('test loss {:.3f}'.format(loss.item()))\n",
350
+ "\n",
351
+ "\n",
352
+ "# load best\n",
353
+ "print(f'Best Epoch: {rmses.index(min(rmses))}')\n",
354
+ "model.load_state_dict(torch.load('best.pth'))"
355
+ ]
356
+ },
357
+ {
358
+ "cell_type": "code",
359
+ "execution_count": null,
360
+ "metadata": {
361
+ "id": "ccbxnVyQp3zc"
362
+ },
363
+ "outputs": [],
364
+ "source": [
365
+ "# 予測\n",
366
+ "# one-step forecast\n",
367
+ "\n",
368
+ "\n",
369
+ "\n",
370
+ "\n",
371
+ "pred_length = 10\n",
372
+ "\n",
373
+ "def one_step_predict(model, x, pred_length, col_d=None):\n",
374
+ " preds = []\n",
375
+ " model.eval()\n",
376
+ " for i in range(pred_length):\n",
377
+ " pred = model(x)\n",
378
+ " preds.append(pred)\n",
379
+ " new_line = torch.tensor([pred[0, 0], x[0, -1, 1]+1, *col_d])\n",
380
+ "\n",
381
+ " x = torch.cat([x[:, 1:, :], new_line.unsqueeze(0).unsqueeze(0)], dim=1)\n",
382
+ "\n",
383
+ " preds = torch.cat(preds, dim=1)\n",
384
+ " preds = preds.detach().numpy()\n",
385
+ " preds = preds.reshape(-1)\n",
386
+ " return preds\n",
387
+ "\n",
388
+ "import numpy as np\n",
389
+ "import japanize_matplotlib\n",
390
+ "def plot_one_step_predict(model, x, pred_length, show=True, title='', val=None, col_d=None):\n",
391
+ " preds = one_step_predict(model, x[-1,1:].unsqueeze(0), pred_length, col_d)\n",
392
+ " plt.plot(np.arange(len(x)), x[:, -1, 0].numpy())\n",
393
+ " # preds = last value of x + preds\n",
394
+ " # plt scatter for validation datasets (3 dates after the last date)\n",
395
+ " if val is not None:\n",
396
+ " plt.scatter(np.arange(len(x), len(x)+val.shape[0]), val[:, -1, 0].numpy().reshape(-1), color='red')\n",
397
+ "\n",
398
+ " preds = np.concatenate([x[-1, -1, 0].numpy().reshape(-1), preds])\n",
399
+ " plt.plot(np.arange(len(x)-1, len(x)+pred_length), preds)\n",
400
+ " plt.xticks(np.arange(len(x)+pred_length), np.arange(len(x)+pred_length))\n",
401
+ " plt.title(title)\n",
402
+ " plt.ylabel('Value')\n",
403
+ " plt.xlabel('Release time')\n",
404
+ " if show:\n",
405
+ " plt.tight_layout()\n",
406
+ " plt.show()\n",
407
+ "\n"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "code",
412
+ "execution_count": null,
413
+ "metadata": {
414
+ "id": "d1KwJXXxp3zd"
415
+ },
416
+ "outputs": [],
417
+ "source": [
418
+ "plt.figure(figsize=(8, 8))\n",
419
+ "\n",
420
+ "counter = 0\n",
421
+ "for i0, col in enumerate(cols):\n",
422
+ " if i0 == 18:\n",
423
+ " plt.tight_layout()\n",
424
+ " plt.show()\n",
425
+ " counter = 0\n",
426
+ " plt.figure(figsize=(8, 8))\n",
427
+ " plt.subplot(6, 3, counter+1)\n",
428
+ " plot_one_step_predict(model, dfs[i0], 10, show=False, title=col, val=val_dfs[i0], col_d=col_d[i0])\n",
429
+ " counter += 1\n",
430
+ "plt.tight_layout()\n",
431
+ "plt.show()\n",
432
+ "\n",
433
+ "## ここの図を念のため非表示にしました。添付ファイルの図です。"
434
+ ]
435
+ }
436
+ ],
437
+ "metadata": {
438
+ "kernelspec": {
439
+ "display_name": "base",
440
+ "language": "python",
441
+ "name": "python3"
442
+ },
443
+ "language_info": {
444
+ "codemirror_mode": {
445
+ "name": "ipython",
446
+ "version": 3
447
+ },
448
+ "file_extension": ".py",
449
+ "mimetype": "text/x-python",
450
+ "name": "python",
451
+ "nbconvert_exporter": "python",
452
+ "pygments_lexer": "ipython3",
453
+ "version": "3.11.4"
454
+ },
455
+ "colab": {
456
+ "provenance": []
457
+ }
458
+ },
459
+ "nbformat": 4,
460
+ "nbformat_minor": 0
461
+ }