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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"id": "e1bd4b25-0369-48ac-b446-7a7acc0726a3",
|
6 |
+
"metadata": {},
|
7 |
+
"source": [
|
8 |
+
"# Simple Transformer Model for Addition\n",
|
9 |
+
"This notebook demonstrates how to build and train a simple transformer model to perform addition. We'll start by generating a dataset of simple addition equations and then train a transformer model on this dataset."
|
10 |
+
]
|
11 |
+
},
|
12 |
+
{
|
13 |
+
"cell_type": "code",
|
14 |
+
"execution_count": 31,
|
15 |
+
"id": "f4cadf99",
|
16 |
+
"metadata": {},
|
17 |
+
"outputs": [
|
18 |
+
{
|
19 |
+
"name": "stdout",
|
20 |
+
"output_type": "stream",
|
21 |
+
"text": [
|
22 |
+
"Defaulting to user installation because normal site-packages is not writeable\n",
|
23 |
+
"Requirement already satisfied: ipywidgets in /home/silentnova/.local/lib/python3.10/site-packages (8.1.1)\n",
|
24 |
+
"Requirement already satisfied: comm>=0.1.3 in /home/silentnova/.local/lib/python3.10/site-packages (from ipywidgets) (0.2.1)\n",
|
25 |
+
"Requirement already satisfied: ipython>=6.1.0 in /home/silentnova/.local/lib/python3.10/site-packages (from ipywidgets) (8.20.0)\n",
|
26 |
+
"Requirement already satisfied: traitlets>=4.3.1 in /home/silentnova/.local/lib/python3.10/site-packages (from ipywidgets) (5.14.1)\n",
|
27 |
+
"Requirement already satisfied: widgetsnbextension~=4.0.9 in /home/silentnova/.local/lib/python3.10/site-packages (from ipywidgets) (4.0.9)\n",
|
28 |
+
"Requirement already satisfied: jupyterlab-widgets~=3.0.9 in /home/silentnova/.local/lib/python3.10/site-packages (from ipywidgets) (3.0.9)\n",
|
29 |
+
"Requirement already satisfied: decorator in /home/silentnova/.local/lib/python3.10/site-packages (from ipython>=6.1.0->ipywidgets) (5.1.1)\n",
|
30 |
+
"Requirement already satisfied: jedi>=0.16 in /home/silentnova/.local/lib/python3.10/site-packages (from ipython>=6.1.0->ipywidgets) (0.19.1)\n",
|
31 |
+
"Requirement already satisfied: matplotlib-inline in /home/silentnova/.local/lib/python3.10/site-packages (from ipython>=6.1.0->ipywidgets) (0.1.6)\n",
|
32 |
+
"Requirement already satisfied: prompt-toolkit<3.1.0,>=3.0.41 in /home/silentnova/.local/lib/python3.10/site-packages (from ipython>=6.1.0->ipywidgets) (3.0.43)\n",
|
33 |
+
"Requirement already satisfied: pygments>=2.4.0 in /usr/local/lib/python3.10/dist-packages (from ipython>=6.1.0->ipywidgets) (2.17.2)\n",
|
34 |
+
"Requirement already satisfied: stack-data in /home/silentnova/.local/lib/python3.10/site-packages (from ipython>=6.1.0->ipywidgets) (0.6.3)\n",
|
35 |
+
"Requirement already satisfied: exceptiongroup in /home/silentnova/.local/lib/python3.10/site-packages (from ipython>=6.1.0->ipywidgets) (1.2.0)\n",
|
36 |
+
"Requirement already satisfied: pexpect>4.3 in /usr/lib/python3/dist-packages (from ipython>=6.1.0->ipywidgets) (4.8.0)\n",
|
37 |
+
"Requirement already satisfied: parso<0.9.0,>=0.8.3 in /home/silentnova/.local/lib/python3.10/site-packages (from jedi>=0.16->ipython>=6.1.0->ipywidgets) (0.8.3)\n",
|
38 |
+
"Requirement already satisfied: wcwidth in /home/silentnova/.local/lib/python3.10/site-packages (from prompt-toolkit<3.1.0,>=3.0.41->ipython>=6.1.0->ipywidgets) (0.2.13)\n",
|
39 |
+
"Requirement already satisfied: executing>=1.2.0 in /home/silentnova/.local/lib/python3.10/site-packages (from stack-data->ipython>=6.1.0->ipywidgets) (2.0.1)\n",
|
40 |
+
"Requirement already satisfied: asttokens>=2.1.0 in /home/silentnova/.local/lib/python3.10/site-packages (from stack-data->ipython>=6.1.0->ipywidgets) (2.4.1)\n",
|
41 |
+
"Requirement already satisfied: pure-eval in /home/silentnova/.local/lib/python3.10/site-packages (from stack-data->ipython>=6.1.0->ipywidgets) (0.2.2)\n",
|
42 |
+
"Requirement already satisfied: six>=1.12.0 in /usr/lib/python3/dist-packages (from asttokens>=2.1.0->stack-data->ipython>=6.1.0->ipywidgets) (1.16.0)\n",
|
43 |
+
"Defaulting to user installation because normal site-packages is not writeable\n",
|
44 |
+
"Requirement already satisfied: tensorflow in /home/silentnova/.local/lib/python3.10/site-packages (2.15.0.post1)\n",
|
45 |
+
"Requirement already satisfied: absl-py>=1.0.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (2.1.0)\n",
|
46 |
+
"Requirement already satisfied: astunparse>=1.6.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (1.6.3)\n",
|
47 |
+
"Requirement already satisfied: flatbuffers>=23.5.26 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (23.5.26)\n",
|
48 |
+
"Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (0.5.4)\n",
|
49 |
+
"Requirement already satisfied: google-pasta>=0.1.1 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (0.2.0)\n",
|
50 |
+
"Requirement already satisfied: h5py>=2.9.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (3.10.0)\n",
|
51 |
+
"Requirement already satisfied: libclang>=13.0.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (16.0.6)\n",
|
52 |
+
"Requirement already satisfied: ml-dtypes~=0.2.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (0.2.0)\n",
|
53 |
+
"Requirement already satisfied: numpy<2.0.0,>=1.23.5 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (1.26.3)\n",
|
54 |
+
"Requirement already satisfied: opt-einsum>=2.3.2 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (3.3.0)\n",
|
55 |
+
"Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from tensorflow) (23.2)\n",
|
56 |
+
"Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (4.23.4)\n",
|
57 |
+
"Requirement already satisfied: setuptools in /usr/lib/python3/dist-packages (from tensorflow) (59.6.0)\n",
|
58 |
+
"Requirement already satisfied: six>=1.12.0 in /usr/lib/python3/dist-packages (from tensorflow) (1.16.0)\n",
|
59 |
+
"Requirement already satisfied: termcolor>=1.1.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (2.4.0)\n",
|
60 |
+
"Requirement already satisfied: typing-extensions>=3.6.6 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (4.9.0)\n",
|
61 |
+
"Requirement already satisfied: wrapt<1.15,>=1.11.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (1.14.1)\n",
|
62 |
+
"Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (0.35.0)\n",
|
63 |
+
"Requirement already satisfied: grpcio<2.0,>=1.24.3 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (1.60.0)\n",
|
64 |
+
"Requirement already satisfied: tensorboard<2.16,>=2.15 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (2.15.1)\n",
|
65 |
+
"Requirement already satisfied: tensorflow-estimator<2.16,>=2.15.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (2.15.0)\n",
|
66 |
+
"Requirement already satisfied: keras<2.16,>=2.15.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorflow) (2.15.0)\n",
|
67 |
+
"Requirement already satisfied: wheel<1.0,>=0.23.0 in /usr/lib/python3/dist-packages (from astunparse>=1.6.0->tensorflow) (0.37.1)\n",
|
68 |
+
"Requirement already satisfied: google-auth<3,>=1.6.3 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorboard<2.16,>=2.15->tensorflow) (2.26.2)\n",
|
69 |
+
"Requirement already satisfied: google-auth-oauthlib<2,>=0.5 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorboard<2.16,>=2.15->tensorflow) (1.2.0)\n",
|
70 |
+
"Requirement already satisfied: markdown>=2.6.8 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorboard<2.16,>=2.15->tensorflow) (3.5.2)\n",
|
71 |
+
"Requirement already satisfied: requests<3,>=2.21.0 in /usr/lib/python3/dist-packages (from tensorboard<2.16,>=2.15->tensorflow) (2.25.1)\n",
|
72 |
+
"Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorboard<2.16,>=2.15->tensorflow) (0.7.2)\n",
|
73 |
+
"Requirement already satisfied: werkzeug>=1.0.1 in /home/silentnova/.local/lib/python3.10/site-packages (from tensorboard<2.16,>=2.15->tensorflow) (3.0.1)\n",
|
74 |
+
"Requirement already satisfied: cachetools<6.0,>=2.0.0 in /home/silentnova/.local/lib/python3.10/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.16,>=2.15->tensorflow) (5.3.2)\n",
|
75 |
+
"Requirement already satisfied: pyasn1-modules>=0.2.1 in /home/silentnova/.local/lib/python3.10/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.16,>=2.15->tensorflow) (0.3.0)\n",
|
76 |
+
"Requirement already satisfied: rsa<5,>=3.1.4 in /home/silentnova/.local/lib/python3.10/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.16,>=2.15->tensorflow) (4.9)\n",
|
77 |
+
"Requirement already satisfied: requests-oauthlib>=0.7.0 in /home/silentnova/.local/lib/python3.10/site-packages (from google-auth-oauthlib<2,>=0.5->tensorboard<2.16,>=2.15->tensorflow) (1.3.1)\n",
|
78 |
+
"Requirement already satisfied: MarkupSafe>=2.1.1 in /home/silentnova/.local/lib/python3.10/site-packages (from werkzeug>=1.0.1->tensorboard<2.16,>=2.15->tensorflow) (2.1.4)\n",
|
79 |
+
"Requirement already satisfied: pyasn1<0.6.0,>=0.4.6 in /home/silentnova/.local/lib/python3.10/site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<2.16,>=2.15->tensorflow) (0.5.1)\n",
|
80 |
+
"Requirement already satisfied: oauthlib>=3.0.0 in /usr/lib/python3/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<2,>=0.5->tensorboard<2.16,>=2.15->tensorflow) (3.2.0)\n",
|
81 |
+
"Defaulting to user installation because normal site-packages is not writeable\n",
|
82 |
+
"Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (1.26.3)\n"
|
83 |
+
]
|
84 |
+
}
|
85 |
+
],
|
86 |
+
"source": [
|
87 |
+
"!pip install ipywidgets\n",
|
88 |
+
"!pip install tensorflow\n",
|
89 |
+
"!pip install numpy"
|
90 |
+
]
|
91 |
+
},
|
92 |
+
{
|
93 |
+
"cell_type": "markdown",
|
94 |
+
"id": "e799a955-9d61-4809-9fd8-2aec69650d13",
|
95 |
+
"metadata": {},
|
96 |
+
"source": [
|
97 |
+
"## Dataset Generation\n",
|
98 |
+
"We will generate a dataset of simple addition equations. Each equation will be in the form of 'a + b = c' where 'a', 'b', and 'c' are integers."
|
99 |
+
]
|
100 |
+
},
|
101 |
+
{
|
102 |
+
"cell_type": "code",
|
103 |
+
"execution_count": 32,
|
104 |
+
"id": "9374dfb6-f072-44a2-a9d9-233efe87ac7f",
|
105 |
+
"metadata": {},
|
106 |
+
"outputs": [
|
107 |
+
{
|
108 |
+
"name": "stdout",
|
109 |
+
"output_type": "stream",
|
110 |
+
"text": [
|
111 |
+
"Input Equation: 12 + 14 =\n",
|
112 |
+
"Answer: 26;\n",
|
113 |
+
"\n",
|
114 |
+
"Input Equation: 28 + 73 =\n",
|
115 |
+
"Answer: 101;\n",
|
116 |
+
"\n",
|
117 |
+
"Input Equation: 51 + 31 =\n",
|
118 |
+
"Answer: 82;\n",
|
119 |
+
"\n"
|
120 |
+
]
|
121 |
+
}
|
122 |
+
],
|
123 |
+
"source": [
|
124 |
+
"import random\n",
|
125 |
+
"from tensorflow.keras.preprocessing.text import Tokenizer\n",
|
126 |
+
"from tensorflow.keras.preprocessing.sequence import pad_sequences\n",
|
127 |
+
"\n",
|
128 |
+
"def generate_addition_data(num_samples, stop_token=';'):\n",
|
129 |
+
" input_equations = []\n",
|
130 |
+
" answers = []\n",
|
131 |
+
" for _ in range(num_samples):\n",
|
132 |
+
" a = random.randint(0, 99)\n",
|
133 |
+
" b = random.randint(0, 99)\n",
|
134 |
+
" input_eq = f\"{a} + {b} =\"\n",
|
135 |
+
" answer = str(a + b) + stop_token # Append the stop token to each answer\n",
|
136 |
+
" input_equations.append(input_eq)\n",
|
137 |
+
" answers.append(answer)\n",
|
138 |
+
" return input_equations, answers\n",
|
139 |
+
"\n",
|
140 |
+
"num_samples = 500000\n",
|
141 |
+
"input_equations, answers = generate_addition_data(num_samples)\n",
|
142 |
+
"\n",
|
143 |
+
"\n",
|
144 |
+
"num_samples_to_print = 3\n",
|
145 |
+
"for i in range(num_samples_to_print):\n",
|
146 |
+
" print(f\"Input Equation: {input_equations[i]}\")\n",
|
147 |
+
" print(f\"Answer: {answers[i]}\")\n",
|
148 |
+
" print()"
|
149 |
+
]
|
150 |
+
},
|
151 |
+
{
|
152 |
+
"cell_type": "markdown",
|
153 |
+
"id": "95d98ddf-ca76-4139-ab88-af21659f8f7a",
|
154 |
+
"metadata": {},
|
155 |
+
"source": [
|
156 |
+
"## Data Preprocessing\n",
|
157 |
+
"We'll convert the equations into a format suitable for training a transformer model. This includes tokenization and converting tokens to numerical format.\n"
|
158 |
+
]
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"cell_type": "code",
|
162 |
+
"execution_count": 33,
|
163 |
+
"id": "477da248-a90c-4a1d-b307-8a786aab9750",
|
164 |
+
"metadata": {},
|
165 |
+
"outputs": [
|
166 |
+
{
|
167 |
+
"name": "stdout",
|
168 |
+
"output_type": "stream",
|
169 |
+
"text": [
|
170 |
+
"Input Equation: 12 + 14 =\n",
|
171 |
+
"Tokenized Input Sequence: [2, 9, 1, 3, 1, 2, 12, 1, 4]\n",
|
172 |
+
"Padded Input Sequence: [ 2 9 1 3 1 2 12 1 4]\n",
|
173 |
+
"Answer: 26;\n",
|
174 |
+
"Tokenized Answer Sequence: [9, 10, 5]\n",
|
175 |
+
"Padded Answer Sequence: [ 9 10 5 0 0 0 0 0 0]\n",
|
176 |
+
"\n",
|
177 |
+
"Input Equation: 28 + 73 =\n",
|
178 |
+
"Tokenized Input Sequence: [9, 8, 1, 3, 1, 7, 6, 1, 4]\n",
|
179 |
+
"Padded Input Sequence: [9 8 1 3 1 7 6 1 4]\n",
|
180 |
+
"Answer: 101;\n",
|
181 |
+
"Tokenized Answer Sequence: [2, 14, 2, 5]\n",
|
182 |
+
"Padded Answer Sequence: [ 2 14 2 5 0 0 0 0 0]\n",
|
183 |
+
"\n",
|
184 |
+
"Input Equation: 51 + 31 =\n",
|
185 |
+
"Tokenized Input Sequence: [11, 2, 1, 3, 1, 6, 2, 1, 4]\n",
|
186 |
+
"Padded Input Sequence: [11 2 1 3 1 6 2 1 4]\n",
|
187 |
+
"Answer: 82;\n",
|
188 |
+
"Tokenized Answer Sequence: [8, 9, 5]\n",
|
189 |
+
"Padded Answer Sequence: [8 9 5 0 0 0 0 0 0]\n",
|
190 |
+
"\n"
|
191 |
+
]
|
192 |
+
}
|
193 |
+
],
|
194 |
+
"source": [
|
195 |
+
"# Tokenization\n",
|
196 |
+
"tokenizer = Tokenizer(char_level=True) # Adjust tokenizer settings as needed\n",
|
197 |
+
"tokenizer.fit_on_texts(input_equations + answers)\n",
|
198 |
+
"\n",
|
199 |
+
"# Convert to sequences\n",
|
200 |
+
"input_sequences = tokenizer.texts_to_sequences(input_equations)\n",
|
201 |
+
"answer_sequences = tokenizer.texts_to_sequences(answers)\n",
|
202 |
+
"\n",
|
203 |
+
"# Padding sequences\n",
|
204 |
+
"max_len_input = max([len(seq) for seq in input_sequences])\n",
|
205 |
+
"max_len_answer = max([len(seq) for seq in answer_sequences])\n",
|
206 |
+
"max_len = max(max_len_input, max_len_answer)\n",
|
207 |
+
"\n",
|
208 |
+
"input_sequences_padded = pad_sequences(input_sequences, maxlen=max_len, padding='post')\n",
|
209 |
+
"answer_sequences_padded = pad_sequences(answer_sequences, maxlen=max_len, padding='post')\n",
|
210 |
+
"\n",
|
211 |
+
"\n",
|
212 |
+
"\n",
|
213 |
+
"\n",
|
214 |
+
"for i in range(num_samples_to_print):\n",
|
215 |
+
" print(f\"Input Equation: {input_equations[i]}\")\n",
|
216 |
+
" print(f\"Tokenized Input Sequence: {input_sequences[i]}\")\n",
|
217 |
+
" print(f\"Padded Input Sequence: {input_sequences_padded[i]}\")\n",
|
218 |
+
" \n",
|
219 |
+
" print(f\"Answer: {answers[i]}\")\n",
|
220 |
+
" print(f\"Tokenized Answer Sequence: {answer_sequences[i]}\")\n",
|
221 |
+
" print(f\"Padded Answer Sequence: {answer_sequences_padded[i]}\")\n",
|
222 |
+
" \n",
|
223 |
+
" print()"
|
224 |
+
]
|
225 |
+
},
|
226 |
+
{
|
227 |
+
"cell_type": "markdown",
|
228 |
+
"id": "aa090f72",
|
229 |
+
"metadata": {},
|
230 |
+
"source": [
|
231 |
+
"The tokenized input sequences you see are token IDs generated by Keras' Tokenizer. Let me explain how this works:\n",
|
232 |
+
"\n",
|
233 |
+
" - Tokenizer Creation: When we create a Tokenizer instance with char_level=True, the tokenizer treats each unique character as a distinct token.\n",
|
234 |
+
"\n",
|
235 |
+
" - Fitting the Tokenizer: By calling tokenizer.fit_on_texts(input_equations + answers), we are essentially instructing the tokenizer to go through all the characters in our dataset (both the input equations and the answers) and assign a unique integer ID to each different character.\n",
|
236 |
+
"\n",
|
237 |
+
" - Token IDs: The tokenizer then creates a mapping from characters to these integer IDs. For example, it might assign '1' to '+', '2' to '=', '3' to '0', '4' to ';', and so on for all unique characters (including all digits from '0' to '9'). The exact mapping depends on the order in which the characters are encountered and their frequency.\n",
|
238 |
+
"\n",
|
239 |
+
" - Tokenization Process: When we convert the text data into sequences using tokenizer.texts_to_sequences(...), each character in the input is replaced by its corresponding integer ID based on the mapping created by the tokenizer.\n",
|
240 |
+
"\n",
|
241 |
+
"For instance, if the input equation is \"49 + 51 =\", and the tokenizer has assigned '6' to '4', '13' to '9', '1' to ' ', '3' to '+', '12' to '5', and '2' to '=', then the tokenized input sequence for this equation would be [6, 13, 1, 3, 1, 12, 2, 1, 4].\n",
|
242 |
+
"\n",
|
243 |
+
"These token IDs are used throughout the model for processing, and they are crucial for both understanding the input data and generating predictions. The model learns to associate these tokens with their meaning in the context of addition operations."
|
244 |
+
]
|
245 |
+
},
|
246 |
+
{
|
247 |
+
"cell_type": "markdown",
|
248 |
+
"id": "6d89bad6-39a0-49ec-8754-931269ea4701",
|
249 |
+
"metadata": {},
|
250 |
+
"source": [
|
251 |
+
"## Building the Transformer Model\n",
|
252 |
+
"We will define a simple transformer model suitable for our task."
|
253 |
+
]
|
254 |
+
},
|
255 |
+
{
|
256 |
+
"cell_type": "code",
|
257 |
+
"execution_count": 34,
|
258 |
+
"id": "00811e2d-2d60-49be-8c38-e88bf6ecbdfd",
|
259 |
+
"metadata": {},
|
260 |
+
"outputs": [],
|
261 |
+
"source": [
|
262 |
+
"from tensorflow.keras.models import Model\n",
|
263 |
+
"from tensorflow.keras.layers import Input, Embedding, MultiHeadAttention, LayerNormalization, Dropout, Dense\n",
|
264 |
+
"from tensorflow.keras.layers import GlobalAveragePooling1D\n",
|
265 |
+
"from tensorflow.keras.layers import Masking\n",
|
266 |
+
"import tensorflow as tf\n",
|
267 |
+
"\n",
|
268 |
+
"# Transformer block as a custom layer\n",
|
269 |
+
"class TransformerBlock(tf.keras.layers.Layer):\n",
|
270 |
+
" def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):\n",
|
271 |
+
" super(TransformerBlock, self).__init__()\n",
|
272 |
+
" self.att = MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)\n",
|
273 |
+
" self.ffn = tf.keras.Sequential(\n",
|
274 |
+
" [Dense(ff_dim, activation=\"relu\"), Dense(embed_dim),]\n",
|
275 |
+
" )\n",
|
276 |
+
" self.layernorm1 = LayerNormalization(epsilon=1e-6)\n",
|
277 |
+
" self.layernorm2 = LayerNormalization(epsilon=1e-6)\n",
|
278 |
+
" self.dropout1 = Dropout(rate)\n",
|
279 |
+
" self.dropout2 = Dropout(rate)\n",
|
280 |
+
"\n",
|
281 |
+
" def call(self, inputs, training):\n",
|
282 |
+
" attn_output = self.att(inputs, inputs)\n",
|
283 |
+
" attn_output = self.dropout1(attn_output, training=training)\n",
|
284 |
+
" out1 = self.layernorm1(inputs + attn_output)\n",
|
285 |
+
" ffn_output = self.ffn(out1)\n",
|
286 |
+
" ffn_output = self.dropout2(ffn_output, training=training)\n",
|
287 |
+
" return self.layernorm2(out1 + ffn_output)\n"
|
288 |
+
]
|
289 |
+
},
|
290 |
+
{
|
291 |
+
"cell_type": "code",
|
292 |
+
"execution_count": 35,
|
293 |
+
"id": "4c69b1b4-070c-4cdc-8f33-ceb7f8fcaa63",
|
294 |
+
"metadata": {},
|
295 |
+
"outputs": [
|
296 |
+
{
|
297 |
+
"name": "stdout",
|
298 |
+
"output_type": "stream",
|
299 |
+
"text": [
|
300 |
+
"Model: \"model_3\"\n",
|
301 |
+
"_________________________________________________________________\n",
|
302 |
+
" Layer (type) Output Shape Param # \n",
|
303 |
+
"=================================================================\n",
|
304 |
+
" input_4 (InputLayer) [(None, 9)] 0 \n",
|
305 |
+
" \n",
|
306 |
+
" embedding_3 (Embedding) (None, 9, 64) 960 \n",
|
307 |
+
" \n",
|
308 |
+
" masking (Masking) (None, 9, 64) 0 \n",
|
309 |
+
" \n",
|
310 |
+
" transformer_block_3 (Trans (None, 9, 64) 446336 \n",
|
311 |
+
" formerBlock) \n",
|
312 |
+
" \n",
|
313 |
+
" global_average_pooling1d_3 (None, 64) 0 \n",
|
314 |
+
" (GlobalAveragePooling1D) \n",
|
315 |
+
" \n",
|
316 |
+
" dense_11 (Dense) (None, 15) 975 \n",
|
317 |
+
" \n",
|
318 |
+
"=================================================================\n",
|
319 |
+
"Total params: 448271 (1.71 MB)\n",
|
320 |
+
"Trainable params: 448271 (1.71 MB)\n",
|
321 |
+
"Non-trainable params: 0 (0.00 Byte)\n",
|
322 |
+
"_________________________________________________________________\n"
|
323 |
+
]
|
324 |
+
}
|
325 |
+
],
|
326 |
+
"source": [
|
327 |
+
"vocab_size = len(tokenizer.word_index) + 1\n",
|
328 |
+
"embedding_dim = 64\n",
|
329 |
+
"num_heads = 2\n",
|
330 |
+
"ff_dim = 3200\n",
|
331 |
+
"\n",
|
332 |
+
"\n",
|
333 |
+
"inputs = Input(shape=(max_len,))\n",
|
334 |
+
"x = Embedding(vocab_size, embedding_dim)(inputs)\n",
|
335 |
+
"x = Masking(mask_value=0)(x) # Add Masking layer after Embedding\n",
|
336 |
+
"x = TransformerBlock(embedding_dim, num_heads, ff_dim)(x)\n",
|
337 |
+
"x = GlobalAveragePooling1D()(x)\n",
|
338 |
+
"outputs = Dense(vocab_size, activation='softmax')(x)\n",
|
339 |
+
"\n",
|
340 |
+
"model = Model(inputs=inputs, outputs=outputs)\n",
|
341 |
+
"model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n",
|
342 |
+
"model.summary()"
|
343 |
+
]
|
344 |
+
},
|
345 |
+
{
|
346 |
+
"cell_type": "markdown",
|
347 |
+
"id": "8f08462c-97c9-4588-80d1-80f818fe0269",
|
348 |
+
"metadata": {},
|
349 |
+
"source": [
|
350 |
+
"## Model Training\n",
|
351 |
+
"We will now train the transformer model on our generated dataset.\n"
|
352 |
+
]
|
353 |
+
},
|
354 |
+
{
|
355 |
+
"cell_type": "code",
|
356 |
+
"execution_count": 36,
|
357 |
+
"id": "913ac294-5117-4b7f-842d-7af2c1a437f7",
|
358 |
+
"metadata": {
|
359 |
+
"scrolled": true
|
360 |
+
},
|
361 |
+
"outputs": [
|
362 |
+
{
|
363 |
+
"name": "stdout",
|
364 |
+
"output_type": "stream",
|
365 |
+
"text": [
|
366 |
+
"train_input shape: (400000, 9)\n",
|
367 |
+
"val_input shape: (100000, 9)\n",
|
368 |
+
"train_answers_one_hot shape: (400000, 15)\n",
|
369 |
+
"val_answers_one_hot shape: (100000, 15)\n",
|
370 |
+
"Epoch 1/10\n",
|
371 |
+
"12500/12500 [==============================] - 102s 8ms/step - loss: 0.9361 - accuracy: 0.6122 - val_loss: 0.8255 - val_accuracy: 0.6275\n",
|
372 |
+
"Epoch 2/10\n",
|
373 |
+
"12500/12500 [==============================] - 104s 8ms/step - loss: 0.8035 - accuracy: 0.6288 - val_loss: 0.7792 - val_accuracy: 0.6329\n",
|
374 |
+
"Epoch 3/10\n",
|
375 |
+
"12500/12500 [==============================] - 104s 8ms/step - loss: 0.7768 - accuracy: 0.6330 - val_loss: 0.7589 - val_accuracy: 0.6299\n",
|
376 |
+
"Epoch 4/10\n",
|
377 |
+
"12500/12500 [==============================] - 104s 8ms/step - loss: 0.7650 - accuracy: 0.6339 - val_loss: 0.7563 - val_accuracy: 0.6328\n",
|
378 |
+
"Epoch 5/10\n",
|
379 |
+
"12500/12500 [==============================] - 96s 8ms/step - loss: 0.7587 - accuracy: 0.6343 - val_loss: 0.7631 - val_accuracy: 0.6364\n",
|
380 |
+
"Epoch 6/10\n",
|
381 |
+
"12500/12500 [==============================] - 15804s 1s/step - loss: 0.7546 - accuracy: 0.6360 - val_loss: 0.7520 - val_accuracy: 0.6338\n",
|
382 |
+
"Epoch 7/10\n",
|
383 |
+
"12500/12500 [==============================] - 117s 9ms/step - loss: 0.7523 - accuracy: 0.6359 - val_loss: 0.7477 - val_accuracy: 0.6353\n",
|
384 |
+
"Epoch 8/10\n",
|
385 |
+
"12500/12500 [==============================] - 118s 9ms/step - loss: 0.7500 - accuracy: 0.6359 - val_loss: 0.7687 - val_accuracy: 0.6251\n",
|
386 |
+
"Epoch 9/10\n",
|
387 |
+
"12500/12500 [==============================] - 109s 9ms/step - loss: 0.7487 - accuracy: 0.6364 - val_loss: 0.7486 - val_accuracy: 0.6348\n",
|
388 |
+
"Epoch 10/10\n",
|
389 |
+
"12500/12500 [==============================] - 89s 7ms/step - loss: 0.7477 - accuracy: 0.6360 - val_loss: 0.7479 - val_accuracy: 0.6314\n"
|
390 |
+
]
|
391 |
+
}
|
392 |
+
],
|
393 |
+
"source": [
|
394 |
+
"# Splitting dataset into training and validation\n",
|
395 |
+
"train_size = int(0.8 * len(input_sequences_padded))\n",
|
396 |
+
"train_input = input_sequences_padded[:train_size]\n",
|
397 |
+
"train_answers = answer_sequences_padded[:train_size]\n",
|
398 |
+
"\n",
|
399 |
+
"\n",
|
400 |
+
"val_input = input_sequences_padded[train_size:]\n",
|
401 |
+
"val_answers = answer_sequences_padded[train_size:]\n",
|
402 |
+
"\n",
|
403 |
+
"\n",
|
404 |
+
"import numpy as np\n",
|
405 |
+
"from tensorflow.keras.utils import to_categorical\n",
|
406 |
+
"\n",
|
407 |
+
"# Assuming each entry in your target data is an integer class label\n",
|
408 |
+
"num_classes = 15 # as per your model's output\n",
|
409 |
+
"\n",
|
410 |
+
"\n",
|
411 |
+
"\n",
|
412 |
+
"# Flatten the target data\n",
|
413 |
+
"train_answers_flattened = train_answers[:, 0] # Assuming the class label is in the first column\n",
|
414 |
+
"val_answers_flattened = val_answers[:, 0]\n",
|
415 |
+
"\n",
|
416 |
+
"# Apply one-hot encoding\n",
|
417 |
+
"train_answers_one_hot = to_categorical(train_answers_flattened, num_classes=num_classes)\n",
|
418 |
+
"val_answers_one_hot = to_categorical(val_answers_flattened, num_classes=num_classes)\n",
|
419 |
+
"\n",
|
420 |
+
"\n",
|
421 |
+
"\n",
|
422 |
+
"print(\"train_input shape:\", train_input.shape)\n",
|
423 |
+
"print(\"val_input shape:\", val_input.shape)\n",
|
424 |
+
"print(\"train_answers_one_hot shape:\", train_answers_one_hot.shape)\n",
|
425 |
+
"print(\"val_answers_one_hot shape:\", val_answers_one_hot.shape)\n",
|
426 |
+
"\n",
|
427 |
+
"\n",
|
428 |
+
"\n",
|
429 |
+
"\n",
|
430 |
+
"# Training\n",
|
431 |
+
"epochs = 10 # Adjust as needed\n",
|
432 |
+
"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n",
|
433 |
+
"\n",
|
434 |
+
"# Then continue with training\n",
|
435 |
+
"history = model.fit(train_input, train_answers_one_hot, validation_data=(val_input, val_answers_one_hot), epochs=epochs, batch_size=32)\n"
|
436 |
+
]
|
437 |
+
},
|
438 |
+
{
|
439 |
+
"cell_type": "markdown",
|
440 |
+
"id": "cc146793-29e8-4bda-9423-197d05cc12f7",
|
441 |
+
"metadata": {},
|
442 |
+
"source": [
|
443 |
+
"## Prediction"
|
444 |
+
]
|
445 |
+
},
|
446 |
+
{
|
447 |
+
"cell_type": "code",
|
448 |
+
"execution_count": 37,
|
449 |
+
"id": "353ef3f0-3e85-4934-99ab-4a108f3e3cc5",
|
450 |
+
"metadata": {},
|
451 |
+
"outputs": [
|
452 |
+
{
|
453 |
+
"name": "stdout",
|
454 |
+
"output_type": "stream",
|
455 |
+
"text": [
|
456 |
+
"1/1 [==============================] - 0s 87ms/step\n",
|
457 |
+
"1/1 [==============================] - 0s 12ms/step\n",
|
458 |
+
"1/1 [==============================] - 0s 12ms/step\n",
|
459 |
+
"1/1 [==============================] - 0s 11ms/step\n",
|
460 |
+
"1/1 [==============================] - 0s 12ms/step\n",
|
461 |
+
"1/1 [==============================] - 0s 12ms/step\n",
|
462 |
+
"1/1 [==============================] - 0s 11ms/step\n",
|
463 |
+
"1/1 [==============================] - 0s 11ms/step\n",
|
464 |
+
"1/1 [==============================] - 0s 11ms/step\n",
|
465 |
+
"1/1 [==============================] - 0s 11ms/step\n",
|
466 |
+
"Predicted result: 9114461135\n"
|
467 |
+
]
|
468 |
+
}
|
469 |
+
],
|
470 |
+
"source": [
|
471 |
+
"def predict_until_stop(model, tokenizer, input_text, max_length=10, stop_token=';'):\n",
|
472 |
+
" # Tokenizing the input\n",
|
473 |
+
" input_seq = tokenizer.texts_to_sequences([input_text])\n",
|
474 |
+
" # Padding the sequence\n",
|
475 |
+
" input_padded = pad_sequences(input_seq, maxlen=max_len, padding='post')\n",
|
476 |
+
"\n",
|
477 |
+
" predicted_sequence = []\n",
|
478 |
+
" for _ in range(max_length):\n",
|
479 |
+
" # Make a prediction\n",
|
480 |
+
" prediction = model.predict(input_padded)\n",
|
481 |
+
" predicted_token_index = np.argmax(prediction, axis=1)[0]\n",
|
482 |
+
" predicted_token = tokenizer.index_word[predicted_token_index]\n",
|
483 |
+
"\n",
|
484 |
+
" # Append to the sequence and break if stop token is predicted\n",
|
485 |
+
" if predicted_token == stop_token:\n",
|
486 |
+
" break\n",
|
487 |
+
" predicted_sequence.append(predicted_token)\n",
|
488 |
+
"\n",
|
489 |
+
" # Update the input by shifting left and adding the new token at the end\n",
|
490 |
+
" input_padded = np.roll(input_padded, -1, axis=1)\n",
|
491 |
+
" input_padded[0, -1] = predicted_token_index\n",
|
492 |
+
"\n",
|
493 |
+
" return ''.join(predicted_sequence)\n",
|
494 |
+
"\n",
|
495 |
+
"# Example usage\n",
|
496 |
+
"new_input = \"73 + 22 =\"\n",
|
497 |
+
"predicted_result = predict_until_stop(model, tokenizer, new_input, max_length=10)\n",
|
498 |
+
"print(\"Predicted result:\", predicted_result)"
|
499 |
+
]
|
500 |
+
}
|
501 |
+
],
|
502 |
+
"metadata": {
|
503 |
+
"kernelspec": {
|
504 |
+
"display_name": "Python 3 (ipykernel)",
|
505 |
+
"language": "python",
|
506 |
+
"name": "python3"
|
507 |
+
},
|
508 |
+
"language_info": {
|
509 |
+
"codemirror_mode": {
|
510 |
+
"name": "ipython",
|
511 |
+
"version": 3
|
512 |
+
},
|
513 |
+
"file_extension": ".py",
|
514 |
+
"mimetype": "text/x-python",
|
515 |
+
"name": "python",
|
516 |
+
"nbconvert_exporter": "python",
|
517 |
+
"pygments_lexer": "ipython3",
|
518 |
+
"version": "3.10.12"
|
519 |
+
}
|
520 |
+
},
|
521 |
+
"nbformat": 4,
|
522 |
+
"nbformat_minor": 5
|
523 |
+
}
|