RasaBh commited on
Commit
9a9d6c7
·
1 Parent(s): a40fc21
Files changed (1) hide show
  1. A9/A9.ipynb +337 -0
A9/A9.ipynb ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 35,
6
+ "id": "6d803f08-aa4b-40b1-8dc5-8dac097ffd17",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import os\n",
11
+ "import zipfile\n",
12
+ "import io\n",
13
+ "from pathlib import Path\n",
14
+ "\n",
15
+ "import numpy as np\n",
16
+ "import pandas as pd\n",
17
+ "import matplotlib.pyplot as plt\n",
18
+ "\n",
19
+ "import tensorflow as tf\n",
20
+ "from tensorflow import keras\n",
21
+ "from tensorflow.keras import layers, regularizers"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": 36,
27
+ "id": "68a45206-e160-4bd6-ab84-f3a60ef04fb9",
28
+ "metadata": {},
29
+ "outputs": [
30
+ {
31
+ "name": "stdout",
32
+ "output_type": "stream",
33
+ "text": [
34
+ "Input: 26 \tOutput:13\n",
35
+ "Joints: 13\n"
36
+ ]
37
+ }
38
+ ],
39
+ "source": [
40
+ "# Load Kinect movement data\n",
41
+ "\n",
42
+ "JOINTS = [\"head\", \"left_shoulder\", \"left_elbow\", \"right_shoulder\", \"right_elbow\",\n",
43
+ " \"left_hand\", \"right_hand\", \"left_hip\", \"right_hip\", \"left_knee\", \"right_knee\",\n",
44
+ " \"left_foot\", \"right_foot\",\n",
45
+ "]\n",
46
+ "N_JOINTS = len(JOINTS) # total number of body joints\n",
47
+ "N_INPUT = N_JOINTS * 2 # input for each joint(x and y)\n",
48
+ "N_OUTPUT = N_JOINTS * 1 # output/target z coordiante\n",
49
+ "print(f'Input: {N_INPUT} \\tOutput:{N_OUTPUT}')\n",
50
+ "print(f'Joints: {N_JOINTS}')"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": 43,
56
+ "id": "7e950179-3350-4cd5-a9e5-98679259e049",
57
+ "metadata": {},
58
+ "outputs": [],
59
+ "source": [
60
+ "# Loads single csv file and splits into input and target array\n",
61
+ "def load_single_csv(filepath_or_bytes):\n",
62
+ " if isinstance(filepath_or_bytes, (str, os.PathLike)):\n",
63
+ " df = pd.read_csv(filepath_or_bytes)\n",
64
+ " else:\n",
65
+ " df = pd.read_csv(io.BytesIO(filepath_or_bytes))\n",
66
+ " df.columns = df.columns.str.strip() \n",
67
+ "\n",
68
+ " x_cols = [f\"{j}_x\" for j in JOINTS]\n",
69
+ " y_cols = [f\"{j}_y\" for j in JOINTS]\n",
70
+ " z_cols = [f\"{j}_z\" for j in JOINTS]\n",
71
+ "\n",
72
+ " xy_cols = []\n",
73
+ " for j in JOINTS:\n",
74
+ " xy_cols += [f\"{j}_x\", f\"{j}_y\"]\n",
75
+ "\n",
76
+ " X = df[xy_cols].values.astype(np.float32) # input\n",
77
+ " y = df[z_cols].values.astype(np.float32) # Target\n",
78
+ "\n",
79
+ " return X, y"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": 44,
85
+ "id": "a048829e-8e40-40ef-9cf1-5b18b2c804cd",
86
+ "metadata": {},
87
+ "outputs": [],
88
+ "source": [
89
+ "# load all csv file from the folder\n",
90
+ "def load_all_sequences(folder_path):\n",
91
+ " sequences, file_names = [], []\n",
92
+ "\n",
93
+ " # Get all CSV files in the folder\n",
94
+ " csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv')]\n",
95
+ " csv_files.sort()\n",
96
+ " \n",
97
+ " print(f\"Found {len(csv_files)} CSV files in folder.\")\n",
98
+ "\n",
99
+ " for name in csv_files:\n",
100
+ " file_path = os.path.join(folder_path, name)\n",
101
+ " \n",
102
+ " with open(file_path, 'rb') as f:\n",
103
+ " raw = f.read()\n",
104
+ " \n",
105
+ " X, y = load_single_csv(raw)\n",
106
+ " \n",
107
+ " sequences.append((X, y)) # stores as (input,target) \n",
108
+ " file_names.append(name)\n",
109
+ "\n",
110
+ " return sequences, file_names"
111
+ ]
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "execution_count": 45,
116
+ "id": "adfcb71f-e762-4440-b0d4-85669201957a",
117
+ "metadata": {},
118
+ "outputs": [],
119
+ "source": [
120
+ "# For Dense MLP model, which treats each frame independently\n",
121
+ "def flatten_sequences(sequences):\n",
122
+ " X_flat = np.concatenate([s[0] for s in sequences], axis=0)\n",
123
+ " y_flat = np.concatenate([s[1] for s in sequences], axis=0)\n",
124
+ " return X_flat, y_flat\n"
125
+ ]
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "execution_count": 46,
130
+ "id": "686a1d16-09bd-44c5-8c92-91f1dd89b4a5",
131
+ "metadata": {},
132
+ "outputs": [],
133
+ "source": [
134
+ "# Create fixed-length windows of consecutive frames from each session for conv1d, lstm and gru\n",
135
+ "def make_windowed_sequences(sequences, window_size=30, stride=1):\n",
136
+ " X_list, y_list = [], []\n",
137
+ " for X, y in sequences:\n",
138
+ " n = len(X)\n",
139
+ " for start in range(0, n - window_size + 1, stride):\n",
140
+ " X_list.append(X[start : start + window_size])\n",
141
+ " y_list.append(y[start : start + window_size])\n",
142
+ "\n",
143
+ " X_seq = np.array(X_list, dtype=np.float32) # (N, window, 26)\n",
144
+ " y_seq = np.array(y_list, dtype=np.float32) # (N, window, 13)\n",
145
+ " return X_seq, y_seq\n"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "execution_count": 47,
151
+ "id": "8305831b-5824-436e-bf22-e78c775963eb",
152
+ "metadata": {},
153
+ "outputs": [
154
+ {
155
+ "name": "stdout",
156
+ "output_type": "stream",
157
+ "text": [
158
+ "Found 179 CSV files in folder.\n",
159
+ "\n",
160
+ "Flat dataset: X=(24005, 26) y=(24005, 13)\n",
161
+ "Windowed dataset: X=(3831, 30, 26) y_last=(3831, 13)\n"
162
+ ]
163
+ }
164
+ ],
165
+ "source": [
166
+ "REPO_ROOT = os.path.abspath(os.path.join(os.getcwd(), '..'))\n",
167
+ "DATA_DIR = os.path.join(REPO_ROOT, 'Datasets_all') \n",
168
+ "KINECT_DATA_PATH = os.path.join(DATA_DIR, 'kinect_good_preprocessed')\n",
169
+ "\n",
170
+ "# sequences contain list of tuples (X,y)\n",
171
+ "sequences, file_names = load_all_sequences(KINECT_DATA_PATH)\n",
172
+ "\n",
173
+ "# Frame-level flat data (for Dense models)\n",
174
+ "X_flat, y_flat = flatten_sequences(sequences)\n",
175
+ "print(f\"\\nFlat dataset: X={X_flat.shape} y={y_flat.shape}\")\n",
176
+ "\n",
177
+ "# Windowed sequences (for Conv1D / LSTM / GRU models)\n",
178
+ "WINDOW_SIZE = 30\n",
179
+ "X_seq, y_seq = make_windowed_sequences(sequences, window_size=WINDOW_SIZE, stride=5)\n",
180
+ "y_seq_last = y_seq[:, -1, :] # (N, 13)\n",
181
+ "print(f\"Windowed dataset: X={X_seq.shape} y_last={y_seq_last.shape}\")"
182
+ ]
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "execution_count": 42,
187
+ "id": "90dd98c3-e87c-47e5-aee4-5b453ab291a7",
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "# Define Deep Learning network architectures\n",
192
+ "\n",
193
+ "# DEnse MLP\n",
194
+ "\n",
195
+ "def build_dense_model( hidden_units=(128, 64), activation=\"relu\", dropout_rate=0.2,\n",
196
+ " l2_reg=1e-4,optimizer=\"adam\", loss=\"mse\",\n",
197
+ "):\n",
198
+ " inputs = keras.Input(shape=(N_INPUT,), name=\"xy_input\")\n",
199
+ " x = inputs\n",
200
+ " for i, units in enumerate(hidden_units):\n",
201
+ " x = layers.Dense(\n",
202
+ " units,\n",
203
+ " activation=activation,\n",
204
+ " kernel_regularizer=regularizers.l2(l2_reg) if l2_reg else None,\n",
205
+ " name=f\"dense_{i+1}\",\n",
206
+ " )(x)\n",
207
+ " if dropout_rate > 0:\n",
208
+ " x = layers.Dropout(dropout_rate, name=f\"dropout_{i+1}\")(x)\n",
209
+ "\n",
210
+ " outputs = layers.Dense(N_OUTPUT, activation=\"linear\", name=\"z_output\")(x)\n",
211
+ " model = keras.Model(inputs, outputs, name=\"DenseModel\")\n",
212
+ " return model\n"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "execution_count": 23,
218
+ "id": "2f525503-f9ef-42e6-bdeb-1df33d168410",
219
+ "metadata": {},
220
+ "outputs": [],
221
+ "source": [
222
+ "# Conv1D CNN\n",
223
+ "\n",
224
+ "def build_conv1d_model(filters=(64, 128), kernel_size=3, pool_size=2, dense_units=(64,),\n",
225
+ " activation=\"relu\", dropout_rate=0.2,optimizer=\"adam\", loss=\"mse\",\n",
226
+ "):\n",
227
+ " inputs = keras.Input(shape=(WINDOW_SIZE, N_INPUT), name=\"xy_seq_input\")\n",
228
+ " x = inputs\n",
229
+ " for i, f in enumerate(filters):\n",
230
+ " x = layers.Conv1D(f, kernel_size, activation=activation, padding=\"same\",\n",
231
+ " name=f\"conv_{i+1}\")(x)\n",
232
+ " x = layers.MaxPooling1D(pool_size, padding=\"same\", name=f\"pool_{i+1}\")(x)\n",
233
+ " if dropout_rate > 0:\n",
234
+ " x = layers.Dropout(dropout_rate, name=f\"drop_conv_{i+1}\")(x)\n",
235
+ "\n",
236
+ " x = layers.GlobalAveragePooling1D(name=\"gap\")(x)\n",
237
+ "\n",
238
+ " for i, units in enumerate(dense_units):\n",
239
+ " x = layers.Dense(units, activation=activation, name=f\"fc_{i+1}\")(x)\n",
240
+ " if dropout_rate > 0:\n",
241
+ " x = layers.Dropout(dropout_rate, name=f\"drop_fc_{i+1}\")(x)\n",
242
+ "\n",
243
+ " outputs = layers.Dense(N_OUTPUT, activation=\"linear\", name=\"z_output\")(x)\n",
244
+ " model = keras.Model(inputs, outputs, name=\"Conv1DModel\")\n",
245
+ " return model"
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "execution_count": 24,
251
+ "id": "7d8b4b93-bd1a-4443-aa87-c4f5f39b22b9",
252
+ "metadata": {},
253
+ "outputs": [],
254
+ "source": [
255
+ "# layers.LSTM\n",
256
+ "\n",
257
+ "def build_lstm_model(lstm_units=(64, 32), dense_units=(32,), activation=\"tanh\",\n",
258
+ " dropout_rate=0.2, recurrent_dropout=0.0, optimizer=\"adam\", loss=\"mse\",\n",
259
+ "):\n",
260
+ " inputs = keras.Input(shape=(WINDOW_SIZE, N_INPUT), name=\"xy_seq_input\")\n",
261
+ " x = inputs\n",
262
+ " for i, units in enumerate(lstm_units):\n",
263
+ " return_sequences = (i < len(lstm_units) - 1) \n",
264
+ " x = layers.LSTM(\n",
265
+ " units,\n",
266
+ " return_sequences=return_sequences,\n",
267
+ " dropout=dropout_rate,\n",
268
+ " recurrent_dropout=recurrent_dropout,\n",
269
+ " name=f\"lstm_{i+1}\",\n",
270
+ " )(x)\n",
271
+ "\n",
272
+ " for i, units in enumerate(dense_units):\n",
273
+ " x = layers.Dense(units, activation=\"relu\", name=f\"fc_{i+1}\")(x)\n",
274
+ " if dropout_rate > 0:\n",
275
+ " x = layers.Dropout(dropout_rate, name=f\"drop_fc_{i+1}\")(x)\n",
276
+ "\n",
277
+ " outputs = layers.Dense(N_OUTPUT, activation=\"linear\", name=\"z_output\")(x)\n",
278
+ " model = keras.Model(inputs, outputs, name=\"LSTMModel\")\n",
279
+ " return model"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "execution_count": 25,
285
+ "id": "1841d0b4-4805-4667-91a2-00c8d3696e77",
286
+ "metadata": {},
287
+ "outputs": [],
288
+ "source": [
289
+ "# layers.GRU \n",
290
+ "\n",
291
+ "def build_gru_model(gru_units=(64, 32), dense_units=(32,), dropout_rate=0.2, \n",
292
+ " recurrent_dropout=0.0, optimizer=\"adam\", loss=\"mse\",):\n",
293
+ " inputs = keras.Input(shape=(WINDOW_SIZE, N_INPUT), name=\"xy_seq_input\")\n",
294
+ " x = inputs\n",
295
+ " for i, units in enumerate(gru_units):\n",
296
+ " return_sequences = (i < len(gru_units) - 1)\n",
297
+ " x = layers.GRU(\n",
298
+ " units,\n",
299
+ " return_sequences=return_sequences,\n",
300
+ " dropout=dropout_rate,\n",
301
+ " recurrent_dropout=recurrent_dropout,\n",
302
+ " name=f\"gru_{i+1}\",\n",
303
+ " )(x)\n",
304
+ "\n",
305
+ " for i, units in enumerate(dense_units):\n",
306
+ " x = layers.Dense(units, activation=\"relu\", name=f\"fc_{i+1}\")(x)\n",
307
+ " if dropout_rate > 0:\n",
308
+ " x = layers.Dropout(dropout_rate, name=f\"drop_fc_{i+1}\")(x)\n",
309
+ "\n",
310
+ " outputs = layers.Dense(N_OUTPUT, activation=\"linear\", name=\"z_output\")(x)\n",
311
+ " model = keras.Model(inputs, outputs, name=\"GRUModel\")\n",
312
+ " return model"
313
+ ]
314
+ }
315
+ ],
316
+ "metadata": {
317
+ "kernelspec": {
318
+ "display_name": "Python 3 (ipykernel)",
319
+ "language": "python",
320
+ "name": "python3"
321
+ },
322
+ "language_info": {
323
+ "codemirror_mode": {
324
+ "name": "ipython",
325
+ "version": 3
326
+ },
327
+ "file_extension": ".py",
328
+ "mimetype": "text/x-python",
329
+ "name": "python",
330
+ "nbconvert_exporter": "python",
331
+ "pygments_lexer": "ipython3",
332
+ "version": "3.10.11"
333
+ }
334
+ },
335
+ "nbformat": 4,
336
+ "nbformat_minor": 5
337
+ }