diff --git a/README.md b/README.md index fcfc332..1e493b6 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ Trained on [Tatoeba dataset](http://downloads.tatoeba.org/exports/sentences.tar. ### [Neural Machine Translation](neural-machine-translation) -Trained on [500 English-Vietnam](neural-machine-translation/vietnam-train), accuracy table in [neural-machine-translation](neural-machine-translation). +Trained on [English-Vietnam](https://github.com/stefan-it/nmt-en-vi#dataset), accuracy table in [neural-machine-translation](neural-machine-translation). 1. Seq2Seq-manual 2. Seq2Seq-API Greedy diff --git a/neural-machine-translation/1.basic-seq2seq-manual.ipynb b/neural-machine-translation/1.basic-seq2seq-manual.ipynb deleted file mode 100644 index 22a3711..0000000 --- a/neural-machine-translation/1.basic-seq2seq-manual.ipynb +++ /dev/null @@ -1,416 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(reuse=False):\n", - " return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", - " sequence_length=self.X_seq_len,\n", - " dtype = tf.float32)\n", - " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " sequence_length=self.X_seq_len,\n", - " initial_state = last_state,\n", - " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "WARNING:tensorflow:From :6: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", - "Instructions for updating:\n", - "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n" - ] - } - ], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "maxlen_question = max([len(x) for x in X]) * 2\n", - "maxlen_answer = max([len(y) for y in Y]) * 2" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "maxlen_question, maxlen_answer" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int, maxlen):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = maxlen\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(maxlen)\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 1.604396, avg accuracy: 0.881736\n", - "epoch: 2, avg loss: 0.833020, avg accuracy: 0.912527\n", - "epoch: 3, avg loss: 0.771523, avg accuracy: 0.914118\n", - "epoch: 4, avg loss: 0.753420, avg accuracy: 0.913445\n", - "epoch: 5, avg loss: 0.721722, avg accuracy: 0.913764\n", - "epoch: 6, avg loss: 0.699771, avg accuracy: 0.915882\n", - "epoch: 7, avg loss: 0.731362, avg accuracy: 0.915182\n", - "epoch: 8, avg loss: 0.840826, avg accuracy: 0.909773\n", - "epoch: 9, avg loss: 0.744763, avg accuracy: 0.914564\n", - "epoch: 10, avg loss: 0.716952, avg accuracy: 0.915045\n", - "epoch: 11, avg loss: 0.724257, avg accuracy: 0.913836\n", - "epoch: 12, avg loss: 1.140763, avg accuracy: 0.863182\n", - "epoch: 13, avg loss: 0.987183, avg accuracy: 0.909855\n", - "epoch: 14, avg loss: 0.821809, avg accuracy: 0.913555\n", - "epoch: 15, avg loss: 0.750108, avg accuracy: 0.914145\n", - "epoch: 16, avg loss: 0.754669, avg accuracy: 0.915127\n", - "epoch: 17, avg loss: 0.750940, avg accuracy: 0.914536\n", - "epoch: 18, avg loss: 0.734306, avg accuracy: 0.914864\n", - "epoch: 19, avg loss: 0.711908, avg accuracy: 0.916727\n", - "epoch: 20, avg loss: 0.707829, avg accuracy: 0.915255\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " X, Y = shuffle(X, Y)\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k + batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_answer)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)\n", - " predicted, accuracy, loss, _ = sess.run([tf.argmax(model.logits,2),\n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y,\n", - " model.X_seq_len:seq_x,\n", - " model.Y_seq_len:seq_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: there were a lot of risks involved that they talked about during the informed consent portion .\n", - "REAL ANSWER: có rất nhiều nguy cơ liên quan mà họ nói đến trong phần thông báo sự chấp thuận .\n", - "PREDICTED ANSWER: và tôi thể , tôi , , , và . . , và , , , , " . \n", - "\n", - "row 2\n", - "QUESTION: any powerful technology is inherently dual use , and , you know , you get something like synthetic biology , nanobiotechnology , it really compels you , you have to look at both the amateur groups but also the professional groups , because they have better infrastructure , they have better facilities , and they have access to pathogens .\n", - "REAL ANSWER: bất kì kỹ thuật nào cũng như con dao hai lưỡi , và , bạn biết rằng , khi bạn có những thứ như sinh học tổng hợp , công nghệ sinh học nano , bạn buộc phải nhìn vào không chỉ những nhóm nghiệp dư mà cả những nhóm chuyên nghiệp , vì họ có cơ sở hạ tầng tốt hơn , họ có điều kiện thuận lợi hơn , và họ có thể tiếp cận các tác nhân gây bệnh .\n", - "PREDICTED ANSWER: và tôi tôi , tôi , . , , , , , , , , , , , , . , , , , , , , , , , , . một , , , và , và , , . , , , , , , . , , , , và . \n", - "\n", - "row 3\n", - "QUESTION: and it 's not just water that this works with .\n", - "REAL ANSWER: không chỉ có nước\n", - "PREDICTED ANSWER: và tôi là có một \n", - "\n", - "row 4\n", - "QUESTION: but what you 're seeing here is 160 to 175 degrees , and anything over 150 is superhydrophobic .\n", - "REAL ANSWER: chúng ta đang nhìn thấy đây là 160 - 175 độ , và từ 150 độ trở đi là chống thấm cực tốt rồi .\n", - "PREDICTED ANSWER: và tôi tôi , , , . , . chúng , , , , , , . , và . . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/1.basic-seq2seq.ipynb b/neural-machine-translation/1.basic-seq2seq.ipynb new file mode 100644 index 0000000..b1dd3b8 --- /dev/null +++ b/neural-machine-translation/1.basic-seq2seq.ipynb @@ -0,0 +1,875 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(reuse=False):\n", + " return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", + " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", + " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " sequence_length=self.X_seq_len,\n", + " dtype = tf.float32)\n", + " with tf.variable_scope(\"decoder\"):\n", + " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = last_state,\n", + " dtype = tf.float32)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 10:07:25.215215 139646746863424 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 10:07:25.268129 139646746863424 deprecation.py:323] From :10: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 10:07:25.270080 139646746863424 deprecation.py:323] From :25: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 10:07:25.271439 139646746863424 deprecation.py:323] From :28: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 10:07:25.711220 139646746863424 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 10:07:25.721455 139646746863424 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:459: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 10:07:25.840559 139646746863424 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 10:07:25.998797 139646746863424 deprecation.py:323] From :35: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n", + "W0902 10:07:26.965247 139646746863424 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [04:15<00:00, 4.52it/s, accuracy=0.0673, cost=6.98]\n", + "minibatch loop: 100%|██████████| 23/23 [00:02<00:00, 9.61it/s, accuracy=0.0904, cost=6.73]\n", + "minibatch loop: 0%| | 0/1042 [00:00 phút , của nữ nữ thế , khoảng thế thế hành về sự của của của suất trong động trong của đời của của , - tuổi . của cô cô cô cô cô cô phu cô cô cô , , rưỡi đêm đêm trong trong , trong trong . Trung , người năm , , , trong đời . trong đời và giờ . , , - - - . . tôi trong . . Francisco Washington và và và ?\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Chúng là một là một , chuyện . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Chúng là một một kịch robot , được lắp lại . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Chúng tôi tôi cho bạn về về về về , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Nhưng tưởng tượng tiên tiên tiên : đàn đàn ông của của của của . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Chúng ta là cựu , , một một , , đàn ông người người hùng sống nguy trên trên . vọng của của của của quê của và và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Nhưng tưởng tượng ông là một là như , , , , , chính , của sống của , của . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Nhưng ngữ , , tôi vì , , , , , anh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Chúng ta đi vào vào . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Chúng ta chết mất mất từ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Chúng ta là tôi tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Chúng đã bao bao giờ ở ở trong đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng tôi tôi của chúng ta càng nhiều nhiều ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Nhưng tôi tôi bao tôi tôi ! anh mình \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Nhưng tôi của tôi không phải làm nó nó phải . trong . , , và tôi tôi tôi học học , , , , , , , , ta chúng chúng chúng chúng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Chúng đề tiếp theo , , , là là một đường ở trong đầu tiên tiên khấu đắm ngời biển . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Nhưng tôi tôi , , , , khi khi khi khi tuổi - - - giờ - một , , , , , , nhỏ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Nhưng dụ , , , tôi đã của mình trong trong và : và thoát . của và mình và và trong và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Chúng là một là để cô rằng ấy ấy không cho . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Chúng là sau một đã đã ngôn , , , , , đi bờ đường gừng chậu đấm hạc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/10.basic-birnn-seq2seq-contrib-greedy.ipynb b/neural-machine-translation/10.basic-birnn-seq2seq-contrib-greedy.ipynb new file mode 100644 index 0000000..8e2fc4b --- /dev/null +++ b/neural-machine-translation/10.basic-birnn-seq2seq-contrib-greedy.ipynb @@ -0,0 +1,900 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '2'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(size_layer = size_layer, reuse=False):\n", + " return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " \n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embedding, self.X)\n", + " \n", + " for n in range(num_layers):\n", + " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", + " cell_fw = cells(size_layer // 2),\n", + " cell_bw = cells(size_layer // 2),\n", + " inputs = encoder_embedded,\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32,\n", + " scope = 'bidirectional_rnn_%d'%(n))\n", + " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", + " \n", + " bi_state = tf.concat((state_fw, state_bw), -1)\n", + " encoder_state = tuple([bi_state] * num_layers)\n", + " \n", + " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " dense = tf.layers.Dense(to_dict_size)\n", + " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " \n", + " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", + " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", + " sequence_length = self.Y_seq_len,\n", + " time_major = False)\n", + " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = training_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = training_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", + " self.training_logits = training_decoder_output.rnn_output\n", + " \n", + " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", + " embedding = decoder_embedding,\n", + " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", + " end_token = EOS)\n", + " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = predicting_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = predicting_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", + " self.predicting_ids = predicting_decoder_output.sample_id\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "W0902 18:04:46.335828 140274138560320 deprecation.py:323] From :30: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n", + "W0902 18:04:46.336991 140274138560320 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 18:04:46.427003 140274138560320 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 18:04:46.437997 140274138560320 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:459: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 18:04:46.560415 140274138560320 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 18:04:46.946606 140274138560320 deprecation.py:323] From :39: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 18:04:47.630460 140274138560320 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [07:36<00:00, 2.28it/s, accuracy=0.181, cost=5.27]\n", + "minibatch loop: 100%|██████████| 23/23 [00:04<00:00, 4.92it/s, accuracy=0.198, cost=4.88]\n", + "minibatch loop: 0%| | 0/1042 [00:00 phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Không phải là một câu hỏi . Một câu hỏi đơn giản : \" Tôi không thể làm được điều này . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Đó là những con chồn meerkat đã nói , \" Tôi đã gặp Bonnie . Tôi đã làm việc này . Tôi có thể nói rằng , \" Tôi biết không phải là một câu hỏi đơn giản : \" Tôi không thể làm được điều này . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Hãy để tôi giải thích điều này , tôi nghĩ rằng tôi có thể làm gì đó . \" Và tôi đã hỏi \" Bài học \" không \" . \" Tôi đã nghe nói \" Không \" . Tôi sẽ không bao giờ quên được . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy nghĩ về một vài ví dụ về những gì chúng ta biết . SS : Vâng , tôi không biết . Tôi không biết . \" Tôi đã nghe thấy tiếng nói của tôi . Tôi đã làm việc này . Tôi có thể nói rằng , \" Tôi biết không phải là một câu hỏi đơn giản : \" Tôi không thể làm được điều này . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Ông là một người phụ nữ , và tôi đã gặp một người trong phòng thí nghiệm , và tôi nghĩ rằng đó là một vấn đề nghiêm trọng . Một câu chuyện khác . Một câu chuyện khác . Tôi tin rằng vầng sáng tạo ra một cách vô ích . Tuy nhiên , trong một thời gian , một trong những điều mà tôi đã làm . Tôi đã không biết mình đang làm gì ? \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy tưởng tượng bạn có thể thấy rằng nó có thể làm được gì . Tôi sẽ không bao giờ quên được . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Hãy bắt đầu với một câu hỏi . Một câu hỏi đơn giản : \" Bạn có thể làm gì ? \" \" Không \" . \" Tôi đã nghe nói \" Không \" . Tôi sẽ không bao giờ quên được . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Ông ấy bảo cô ấy . \" Và tôi đã nuông chiều . \" Tôi nghĩ đó là một câu hỏi đơn giản : \" Tôi không thể làm được điều này . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Anh ta gọi nó là \" hail \" , và tôi sẽ không bao giờ quên được . \" Tôi sẽ nói \" Tôi đã nghe thấy \" Không \" . \" Tôi đã nghe nói \" Không \" . Tôi sẽ không bao giờ quên được . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Ông ta không biết . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi sẽ không bao giờ quên được . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng những người khác cũng có thể làm được điều này . \" Tôi không biết . Tôi không biết . \" Tôi đã nghe thấy tiếng nói của tôi . Tôi đã làm việc này . Tôi có thể nói rằng , \" Tôi biết không phải là một câu hỏi đơn giản : \" Tôi không thể làm được điều này . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \"\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Mong muốn là gì ? \" \" Không \" . \" Tôi đã nghe nói về nó . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Kinh tế của tôi không phải là vấn đề . \" PM : \" Tôi có thể nói rằng , \" Tôi biết rõ ràng rồi , \" Tôi xin lỗi . Tôi không biết . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Sự quấy rối về cơ bản là một ví dụ . Một lần nữa , nó sẽ đi qua lại . \" Và chúng tôi đã nói rằng , \" Tôi biết không phải là một câu hỏi đơn giản : \" Tôi không thể làm được điều này . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , một người phụ nữ , và tôi đã gặp nhau . Tôi đã làm việc này . Tôi không thể làm được . \" Tôi sẽ nói , \" Tôi biết rằng tôi không thể làm được . \" Tôi sẽ nói \" Vâng ! \" . \" Tôi đã nuông chiều \" . \" Tôi sẽ nói \" Không ! \" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Đối với những người phụ nữ này , tôi đã gặp một người trong phòng thí nghiệm , và tôi nghĩ rằng đó là một vấn đề nghiêm trọng . Một câu chuyện khác . Một câu chuyện khác . Tôi tin rằng vầng sáng tạo ra một cách vô ích . Tuy nhiên , trong một thời gian , một trong những điều mà tôi đã làm . Tôi đã không biết mình đang làm gì ? \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó gọi là \" Sự thiếu hiểu biết trongkhoảng . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm thế . \" Tôi không biết . \" Tôi đã nghe nói về nó . \" Tôi đã làm\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau năm , chúng tôi đã có thể làm được điều này . Tôi sẽ không bao giờ quên được nữa . \" Tôi sẽ nói \" Vâng ! \" . \" Tôi đã nuông chiều \" . \" Tôi sẽ nói \" Không ! \" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/10.basic-birnn-seq2seq-greedy.ipynb b/neural-machine-translation/10.basic-birnn-seq2seq-greedy.ipynb deleted file mode 100644 index 5b8c9cf..0000000 --- a/neural-machine-translation/10.basic-birnn-seq2seq-greedy.ipynb +++ /dev/null @@ -1,439 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "['tôi tiếp tục làm thí nghiệm này 1 thời gian',\n", - " 'và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .']" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "text_to[-2:]" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size, \n", - " from_dict_size, to_dict_size, learning_rate, \n", - " batch_size, dropout = 0.5, beam_width = 15):\n", - " \n", - " def lstm_cell(size, reuse=False):\n", - " return tf.nn.rnn_cell.BasicRNNCell(size, reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", - " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " # encoder\n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " for n in range(num_layers):\n", - " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", - " cell_fw = lstm_cell(size_layer // 2),\n", - " cell_bw = lstm_cell(size_layer // 2),\n", - " inputs = encoder_embedded,\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32,\n", - " scope = 'bidirectional_rnn_%d'%(n))\n", - " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", - " \n", - " bi_state = tf.concat((state_fw, state_bw), -1)\n", - " self.encoder_state = tuple([bi_state] * num_layers)\n", - " \n", - " self.encoder_state = tuple(self.encoder_state[-1] for _ in range(num_layers))\n", - " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " # decoder\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([lstm_cell(size_layer) for _ in range(num_layers)])\n", - " dense_layer = tf.layers.Dense(to_dict_size)\n", - " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", - " inputs = tf.nn.embedding_lookup(decoder_embeddings, decoder_input),\n", - " sequence_length = self.Y_seq_len,\n", - " time_major = False)\n", - " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = training_helper,\n", - " initial_state = self.encoder_state,\n", - " output_layer = dense_layer)\n", - " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = training_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", - " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", - " embedding = decoder_embeddings,\n", - " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", - " end_token = EOS)\n", - " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = predicting_helper,\n", - " initial_state = self.encoder_state,\n", - " output_layer = dense_layer)\n", - " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = predicting_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", - " self.training_logits = training_decoder_output.rnn_output\n", - " self.predicting_ids = predicting_decoder_output.sample_id\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.training_logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "WARNING:tensorflow:From :7: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", - "Instructions for updating:\n", - "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n" - ] - } - ], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(len(sentence))\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 6.625805, avg accuracy: 0.062322\n", - "epoch: 2, avg loss: 5.949493, avg accuracy: 0.094182\n", - "epoch: 3, avg loss: 5.650787, avg accuracy: 0.130502\n", - "epoch: 4, avg loss: 5.315249, avg accuracy: 0.152491\n", - "epoch: 5, avg loss: 4.955022, avg accuracy: 0.186465\n", - "epoch: 6, avg loss: 4.574212, avg accuracy: 0.227074\n", - "epoch: 7, avg loss: 4.171162, avg accuracy: 0.276648\n", - "epoch: 8, avg loss: 3.761979, avg accuracy: 0.335339\n", - "epoch: 9, avg loss: 3.358583, avg accuracy: 0.400926\n", - "epoch: 10, avg loss: 2.987428, avg accuracy: 0.464893\n", - "epoch: 11, avg loss: 2.648347, avg accuracy: 0.539903\n", - "epoch: 12, avg loss: 2.340445, avg accuracy: 0.605599\n", - "epoch: 13, avg loss: 2.074902, avg accuracy: 0.658513\n", - "epoch: 14, avg loss: 1.810939, avg accuracy: 0.716842\n", - "epoch: 15, avg loss: 1.573249, avg accuracy: 0.765040\n", - "epoch: 16, avg loss: 1.346753, avg accuracy: 0.812594\n", - "epoch: 17, avg loss: 1.142557, avg accuracy: 0.856812\n", - "epoch: 18, avg loss: 0.958146, avg accuracy: 0.890111\n", - "epoch: 19, avg loss: 0.788740, avg accuracy: 0.925607\n", - "epoch: 20, avg loss: 0.637479, avg accuracy: 0.957355\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k+batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index ], PAD)\n", - " predicted, accuracy,loss, _ = sess.run([model.predicting_ids, \n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: or , if you had to choose between the last two , which one would you choose ?\n", - "REAL ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ?\n", - "PREDICTED ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ? \n", - "\n", - "row 2\n", - "QUESTION: i kept on doing this for a while .\n", - "REAL ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ?\n", - "PREDICTED ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ? \n", - "\n", - "row 3\n", - "QUESTION: and then , like all good academic projects , i got more funding .\n", - "REAL ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian\n", - "PREDICTED ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian \n", - "\n", - "row 4\n", - "QUESTION: i moved to sounds , electrical shocks -- i even had a pain suit that i could get people to feel much more pain .\n", - "REAL ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .\n", - "PREDICTED ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/11.lstm-birnn-seq2seq-contrib-greedy.ipynb b/neural-machine-translation/11.lstm-birnn-seq2seq-contrib-greedy.ipynb new file mode 100644 index 0000000..0a07a24 --- /dev/null +++ b/neural-machine-translation/11.lstm-birnn-seq2seq-contrib-greedy.ipynb @@ -0,0 +1,909 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '3'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(size_layer = size_layer, reuse=False):\n", + " return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " \n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embedding, self.X)\n", + " \n", + " for n in range(num_layers):\n", + " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", + " cell_fw = cells(size_layer // 2),\n", + " cell_bw = cells(size_layer // 2),\n", + " inputs = encoder_embedded,\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32,\n", + " scope = 'bidirectional_rnn_%d'%(n))\n", + " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", + " \n", + " bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n", + " bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n", + " bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n", + " encoder_state = tuple([bi_lstm_state] * num_layers)\n", + " \n", + " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " dense = tf.layers.Dense(to_dict_size)\n", + " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " \n", + " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", + " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", + " sequence_length = self.Y_seq_len,\n", + " time_major = False)\n", + " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = training_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = training_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", + " self.training_logits = training_decoder_output.rnn_output\n", + " \n", + " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", + " embedding = decoder_embedding,\n", + " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", + " end_token = EOS)\n", + " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = predicting_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = predicting_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", + " self.predicting_ids = predicting_decoder_output.sample_id\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 18:09:45.672424 140511355651904 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 18:09:45.709759 140511355651904 deprecation.py:323] From :10: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 18:09:45.711711 140511355651904 deprecation.py:323] From :30: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n", + "W0902 18:09:45.712890 140511355651904 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 18:09:45.883166 140511355651904 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 18:09:46.477952 140511355651904 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 18:09:47.018548 140511355651904 deprecation.py:323] From :41: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 18:09:47.779454 140511355651904 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n", + "W0902 18:09:48.201711 140511355651904 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [10:15<00:00, 1.69it/s, accuracy=0.157, cost=5.55]\n", + "minibatch loop: 100%|██████████| 23/23 [00:05<00:00, 4.18it/s, accuracy=0.175, cost=5.1] \n", + "minibatch loop: 0%| | 0/1042 [00:00 của thế hệ này , phụ nữ nhất trong cuộc sống của tôi đã trải qua một môi trường lớn nhất liên quan đến việc nâng cấp từ San Francisco , và cô ấy nói với tôi rằng : \" Cô bé đã sống trong một thế giới nhỏ hơn , rồi lại không có gì để lại ở đó , kể cả khi chị đến từ Colombia , cô đã bao giờ nghe tiếng Anh ở khoảng cách giữa hai phút ở San Francisco và nhanh nhất ? Khi còn có thể đi qua được phút ở Ấn Độ và bạn sẽ đi qua hơn một ngàn năm qua . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Không có câu chuyện đó . Không có câu chuyện nào cả . \" . . . . . . . . . . . . . . . \" bất kể là bất cứ thứ gì . \" . . . \" chỉ là kết thúc . \" . . . . . . . . . . . . . . \" chỉ là kết thúc kể từ đó . \" . . . . . . \" . . \" chỉ là kết hợp bình lặng . \" . . . . . . \" chỉ một không gian . \" . . . \" . . . \" chỉ quay lại với nhau . \" . . . \" . . . \" . . . \" chỉ quay lại . \" . . . \" . . . \" - - chỉ . \" . . . . . . . . . \" - - không . \" . . . . . . . . . . . \" chỉ quay lại với nhau . \" . . . \" - - chỉ là kết hợp bình thản . \" .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Câu chuyện của hai câu chuyện vẫn còn đang giao tiếp với nhau . . . . . . \" . . . \" . . . \" . . . \" . . . \" . . . . . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" . \" . \" . \" . \" . \" . \" . . \" . \" . . \" \" chỉ là kết quả quay ngược lại . \" . \" . . \" \" \" \" \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Tôi sẽ kể cho các bạn một vài số liệu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy tưởng tượng điều đầu tiên : người đàn ông : người sống trong đời sống của mình . Hãy làm cho cuộc sống của anh ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Anh ấy là một người đàn ông tên là Jean - len , một niềm tin vào sự tự do của chính mình trong chính quyền và chính trị của mình . Tất cả những người đàn ông của mình là quyền lực . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" \" chính là đức tin . \" . . . \" cũng như vậy . \" . . . \" đó là điều không thể tránh khỏi . \" \" Không chỉ là vậy . \" . . . \" . . . \" - - xin lỗi cho lắm . \" . . \" . . . \" chỉ là một lời khen ngợi . \" . \" . . . \" chỉ là một lời khen ngợi . \" . \" . \" . \" . \" . \" . . \" chỉ là một lời khen ngợi . \"\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy nhìn vào việc ông ấy mang theo một cách hoàn toàn mới để suy nghĩ rằng đó là một sự tồn tại . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" với sự tự do đó . \" . \" . . \" . . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" - - \" đó là điều gì đó với nó . \" \" \" Không chỉ là kết quả . \" . \" . \" . \"\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Từ từ này , bạn bè anh chị , anh em . . . . . chưa từng là người anh hùng . \" . . . . . . . \" vì anh chị ấy . \" . . \" vì vậy thôi . \" . . . \" . . . \" - - \" . . . \" . . . \" - - \" . . . . . \" - - - - - - - - - - xin chào đón đến vậy . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh ấy im lặng qua hoà nhạc . . . . . . . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . . \" . . \" . . . \" - - \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . \" . . . \"\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Ông ấy đã bị liệt dần qua thời gian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" đó là sự tự do của nó . \" . . . \" đó không hề tồn tại được . \" . . . \" \" sâu xa hơn \" . \" . . \" . . \" . . \" . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . . . . . . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Anh ấy là ông của ông . \" . . . \" anh ta là người anh ấy . \" . . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" - - thế nào . \" . . \" - - \" . . . \" - - \" . . . \" - - - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . \" - - \" . . . . \" - -\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi không bao giờ biết được mình thực sự sống ở đó . \" . . . . . \" . . . \" ngày nay . \" . . . \" . . . \" . . . \" . . . \" - - \" đó là một sự sống . \" . . . \" . . \" . . \" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng chúng ta sống trong cuộc sống của chúng ta hơn là những cơn đau của chúng ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" . . \" - - \" - - \" - - \" - - - - - - - - \" - - \" - - điều đó dẫn đến hơn . \" . . . \" đó là điều cần đến đó . \" . . \" . . \" chỉ nhớ thêm nữa . \" - - \" . . . \" . . \" - - \" . . . \" - - \" . . . \" - - ít đi hơn . \" . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Cha tôi không bao giờ quên anh ấy về cuộc sống của tôi . \" . . . . . . . \" - - \" . . . \" . . \" . . \" . . \" \" . . \" . . \" \" . . \" . \" . . \" \" Quay trở lại . \" . . \" - - chưa đến . \" đó là nơi duy nhất . \" . . . \" - - đó là sự phục hồi . \" . . . \" - - đó là sự phục hồi . \" . . . \" . . \" - - điều đó còn tươi đẹp . \" . . . \" chưa bao giờ . \" . . . \" . . . \" . . \" . . \" \" Quay trở lại . \" . . . \" . . \" . . \" . . \" . . \" . . . \" . . . \" . . \" - - \" . . . \" . . . \" . . \" - - \" . . . \" . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Mục đích của tôi không phải là để cho ra đời , và vì vậy , tôi e rằng chúng ta nên bị mắc chứng cho lắm , nhưng chúng ta lại bị mắc kẹt . . . . . . . \" ồn ào hơn . \" . . . \" . . \" . . \" - - chúng ta nói rằng ít nhất là nói về quá trình . \" . . . \" . . . \" . . \" . . \" . . \" . . \" . . \" . . \" . \" - - \" . . . \" . . \" - - - - - - - - - - - \" . . \" . . \" - - \" . . . \" . . \" . . \" - - - - - - \" . . . \" . . \" . . \" - - - - \" . . . \" . . \" - - - - \" . . . \" . . . \" - - - - \" . . . \" . . \" - -\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Khung tiếp theo trong cuộc đua maratông đang trôi qua trong một nhà máy đang chạy ngang qua . cái cửa sổ cá mập khổng lồ . . . . . . . . . . . . . . . . . . sâu trên lưng . \" . . . . . sâu sâu trên lưng tường . \" . . . \" quay lưng lại với nhau . \" . . . \" . . . \" \" quay lưng . \" . . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . . \" . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \"\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , tuổi , khi tôi sống ở một trại đàn ông , một cậu bé tuổi , đã gặp nhau hai lần . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" một câu chuyện khác làm cha mẹ . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Với cô , cô đã nhận được cuộc đời mình để trải nghiệm cuộc sống của cô về một cuộc hôn nhân và gia đình khác . \" vào tháng cô ấy có ở lại với nhau . \" ở Úc . \" . . . . . . . . . . . . . . . . \" . . . \" . . . \" . . . . . . . \" . . . \" . . . \" . ít nữa . \" . . . \" . . . . . . . . . . . . . . . . . . . . . \" Quay lại . \" . . . \" chỉ với các cô gái khác . \" . \" . \" chỉ để duy trì được . \" . . . \" . . \" chỉ với cô ấy . \" . Quay trở lại từ đó . \" . . . \" chỉ từ thiện . \" . . . \" . . . \" . . . \" . . . \" . . . \" chỉ là duy trì một\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó vẫn còn đuổi kịp với vợ mình không tự nhiên . . . . . . . . . . . . . . . \" \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . \" . . . \" . . . \" - - thế đấy . \" - - xin chào đón riêng của mình . \" . . . \" . . . \" - - \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" . . \" . . . . . \" . . . . . \" . . . . . \" . . . . . \" . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau một hồi chuông hồi phục , một cơn ác mộng , một cơn ác mộng , đã được sử dụng khi được đi qua chặng đường . để đánh răng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" bất kỳ chuyện gì đã xảy ra với chúng . \" .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/11.lstm-birnn-seq2seq-greedy.ipynb b/neural-machine-translation/11.lstm-birnn-seq2seq-greedy.ipynb deleted file mode 100644 index 37f7742..0000000 --- a/neural-machine-translation/11.lstm-birnn-seq2seq-greedy.ipynb +++ /dev/null @@ -1,424 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "['tôi tiếp tục làm thí nghiệm này 1 thời gian',\n", - " 'và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .']" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "text_to[-2:]" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size, \n", - " from_dict_size, to_dict_size, learning_rate, \n", - " batch_size, dropout = 0.5, beam_width = 15):\n", - " \n", - " def lstm_cell(size, reuse=False):\n", - " return tf.nn.rnn_cell.LSTMCell(size, initializer=tf.orthogonal_initializer(),\n", - " reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", - " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", - " batch_size = tf.shape(self.X)[0]\n", - " # encoder\n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " for n in range(num_layers):\n", - " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", - " cell_fw = lstm_cell(size_layer // 2),\n", - " cell_bw = lstm_cell(size_layer // 2),\n", - " inputs = encoder_embedded,\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32,\n", - " scope = 'bidirectional_rnn_%d'%(n))\n", - " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", - " \n", - " bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n", - " bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n", - " bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n", - " self.encoder_state = tuple([bi_lstm_state] * num_layers)\n", - " \n", - " self.encoder_state = tuple(self.encoder_state[-1] for _ in range(num_layers))\n", - " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " # decoder\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([lstm_cell(size_layer) for _ in range(num_layers)])\n", - " dense_layer = tf.layers.Dense(to_dict_size)\n", - " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", - " inputs = tf.nn.embedding_lookup(decoder_embeddings, decoder_input),\n", - " sequence_length = self.Y_seq_len,\n", - " time_major = False)\n", - " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = training_helper,\n", - " initial_state = self.encoder_state,\n", - " output_layer = dense_layer)\n", - " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = training_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", - " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", - " embedding = decoder_embeddings,\n", - " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", - " end_token = EOS)\n", - " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = predicting_helper,\n", - " initial_state = self.encoder_state,\n", - " output_layer = dense_layer)\n", - " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = predicting_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", - " self.training_logits = training_decoder_output.rnn_output\n", - " self.predicting_ids = predicting_decoder_output.sample_id\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.training_logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(len(sentence))\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 6.629360, avg accuracy: 0.052543\n", - "epoch: 2, avg loss: 6.113452, avg accuracy: 0.077949\n", - "epoch: 3, avg loss: 5.992076, avg accuracy: 0.088334\n", - "epoch: 4, avg loss: 5.891252, avg accuracy: 0.110016\n", - "epoch: 5, avg loss: 5.819877, avg accuracy: 0.114913\n", - "epoch: 6, avg loss: 5.760571, avg accuracy: 0.120810\n", - "epoch: 7, avg loss: 5.691116, avg accuracy: 0.125001\n", - "epoch: 8, avg loss: 5.606406, avg accuracy: 0.132078\n", - "epoch: 9, avg loss: 5.512288, avg accuracy: 0.137671\n", - "epoch: 10, avg loss: 5.429221, avg accuracy: 0.144395\n", - "epoch: 11, avg loss: 5.329564, avg accuracy: 0.154254\n", - "epoch: 12, avg loss: 5.229920, avg accuracy: 0.158055\n", - "epoch: 13, avg loss: 5.134067, avg accuracy: 0.167498\n", - "epoch: 14, avg loss: 5.047961, avg accuracy: 0.171943\n", - "epoch: 15, avg loss: 4.971337, avg accuracy: 0.174937\n", - "epoch: 16, avg loss: 4.887931, avg accuracy: 0.179139\n", - "epoch: 17, avg loss: 4.813043, avg accuracy: 0.182352\n", - "epoch: 18, avg loss: 4.724143, avg accuracy: 0.187680\n", - "epoch: 19, avg loss: 4.620947, avg accuracy: 0.194570\n", - "epoch: 20, avg loss: 4.508872, avg accuracy: 0.202628\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k+batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index ], PAD)\n", - " predicted, accuracy,loss, _ = sess.run([model.predicting_ids, \n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: or , if you had to choose between the last two , which one would you choose ?\n", - "REAL ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ?\n", - "PREDICTED ANSWER: và tôi có thể làm bạn có thể làm bạn có thể làm bạn có thể làm gì ? \n", - "\n", - "row 2\n", - "QUESTION: i kept on doing this for a while .\n", - "REAL ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ?\n", - "PREDICTED ANSWER: tôi có thể làm , tôi sẽ làm việc đó . \n", - "\n", - "row 3\n", - "QUESTION: and then , like all good academic projects , i got more funding .\n", - "REAL ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian\n", - "PREDICTED ANSWER: tôi tiếp tục làm ra , tôi sẽ làm được tôi ? \n", - "\n", - "row 4\n", - "QUESTION: i moved to sounds , electrical shocks -- i even had a pain suit that i could get people to feel much more pain .\n", - "REAL ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .\n", - "PREDICTED ANSWER: và tôi có thể làm , bạn có thể làm , bạn có thể làm bạn có thể làm bạn có thể làm gì ? \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/12.gru-birnn-seq2seq-contrib-greedy.ipynb b/neural-machine-translation/12.gru-birnn-seq2seq-contrib-greedy.ipynb new file mode 100644 index 0000000..74cc676 --- /dev/null +++ b/neural-machine-translation/12.gru-birnn-seq2seq-contrib-greedy.ipynb @@ -0,0 +1,912 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '2'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/usr/lib/python3/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (3.0.4) doesn't match a supported version!\n", + " RequestsDependencyWarning)\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(size_layer = size_layer, reuse=False):\n", + " return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " \n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embedding, self.X)\n", + " \n", + " for n in range(num_layers):\n", + " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", + " cell_fw = cells(size_layer // 2),\n", + " cell_bw = cells(size_layer // 2),\n", + " inputs = encoder_embedded,\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32,\n", + " scope = 'bidirectional_rnn_%d'%(n))\n", + " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", + " \n", + " bi_state = tf.concat((state_fw, state_bw), -1)\n", + " encoder_state = tuple([bi_state] * num_layers)\n", + " \n", + " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " dense = tf.layers.Dense(to_dict_size)\n", + " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " \n", + " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", + " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", + " sequence_length = self.Y_seq_len,\n", + " time_major = False)\n", + " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = training_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = training_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", + " self.training_logits = training_decoder_output.rnn_output\n", + " \n", + " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", + " embedding = decoder_embedding,\n", + " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", + " end_token = EOS)\n", + " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = predicting_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = predicting_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", + " self.predicting_ids = predicting_decoder_output.sample_id\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 22:39:28.753327 140548336097088 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 22:39:28.794658 140548336097088 deprecation.py:323] From :10: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 22:39:28.796629 140548336097088 deprecation.py:323] From :30: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n", + "W0902 22:39:28.797847 140548336097088 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 22:39:28.886269 140548336097088 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:39:28.898189 140548336097088 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:564: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:39:28.913671 140548336097088 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:574: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:39:29.125241 140548336097088 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 22:39:29.548425 140548336097088 deprecation.py:323] From :39: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 22:39:30.206670 140548336097088 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [09:45<00:00, 1.78it/s, accuracy=0.195, cost=5.15]\n", + "minibatch loop: 100%|██████████| 23/23 [00:05<00:00, 4.35it/s, accuracy=0.22, cost=4.85] \n", + "minibatch loop: 0%| | 0/1042 [00:00 đến , khi cô bé đến tuổi vui hơn và nhanh hơn mẹ đến mức độ cô bé nhỏ bé ? Trong bài diễn thuyết ở châu Phi , bà đã bắt đầu có bài tập về đom đóm mặt trăng và chia sẻ một số hình mẫu mới trong phòng thí nghiệm ? Trong bài nói chuyện này , cô ấy nói rằng , có bao nhiêu vũ trụ và những con gái sống sót ? Trong khi cô ấy đã quay trở lại với năm tuổi . Trong bài nói chuyện vui nhộn này , cô đã tìm ra cách sống sót của mình khi ngồi yên lặng ? Cậu bé này quay trở lại trường . Mùa xuân này , cô ấy đã ngồi tù và cuối cùng cũng có thể tìm thấy chúng ta . Một nửa trong số đó có phải là một em bé . Phải không ? Và tìm cách\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là câu chuyện . . . . . . . . . . . . . . . . . . . . . . . câu chuyện gần đây xong . \" Và qua kịch bản . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Nó tựa như là cô bé vẫn tiếp tục . . . . . đang cùng nhau hỏi . . . khác . \" Như vậy vẫn tiếp tục . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Tôi sẽ nói cho bạn vài lát . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy tưởng tượng lần đầu tiên với người dùng thế này bằng công việc . Hãy làm cho việc làm tương tác của ông . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Là một nhà doanh nghiệp , một người cha đã gây ra tiếng cha hiện đại trong lịch sử đời Thiên tội của ông . . . của cả những kẻ giàu . . . . . . . . của hành tinh . . . . . của ông . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy tưởng tượng khi anh ấy dương cầm , phổi đã phải chịu hậu quả của cuộc đời . Đó là một cuộc hành trình lộn xộn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Từ đây , người ta cho bạn những kẻ cầm tay . Hãy cho ông ấy . . . cho anh ấy . \" Kể cả . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh ấy bốc thăng lên . Hãy đặt im lặng . \" Còn im lặng . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Anh ta đã chết vì lịch sử . Kể cả . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Ông ấy là ông của tôi . \" Em ấy . \" Anh trai đấy . \" Ngày ông . \" Anh ấy đấy . \" Anh trai , ông ấy . \" Và tôi đã viết . \" Anh tôi dùng nốt ' . \" Ngài đã viết . \" Kể cả ông . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi không biết anh ấy luôn sống trong cuộc đời . \" Có vẻ gì cả . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng cuộc sống của chúng ta cao hơn nhiều so với những khuôn khổ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . biểu hiện của ta về mặt sinh học . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Ông ấy không khóc . Tôi sống hết đời mình . Đến thế giới của ông . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Công việc của tôi không phải là vô nghĩa , và đó là cố gợi cho chúng ta những cuốn tiểu thuyết kỳ quặc như thế . . . . . . . . . của nó . Nhưng chúng tôi đã vượt qua nó . \" Dùng cảm giác rất nhỏ . \" Chúng tôi rất thích thú . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Con robot đầu tiên là dây cờ trong một chiếc thuyền . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , sinh con , khi tôi tuổi , đã lớn lên trong tám phút tám chữ số . Cô ấy rất nhỏ - - với gia đình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Trong cuộc sống , cô đã được hưởng một bước chân thực vào cuộc sống mới : Hai phố và New York . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó giúp bà trở thành người không thành công . Nó còn phải giống thiện . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . thành công trong gia đình . . . . . . . . . thành lập gia đình như vậy . Nó sẽ gia thích với bạn . . . . . . . . như một phụ nữ . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau một khoảng thời gian dài , hai dòng sông đã được chuyển thành từ Sao Kim . Kể cả năm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/12.gru-birnn-seq2seq-greedy.ipynb b/neural-machine-translation/12.gru-birnn-seq2seq-greedy.ipynb deleted file mode 100644 index da588f8..0000000 --- a/neural-machine-translation/12.gru-birnn-seq2seq-greedy.ipynb +++ /dev/null @@ -1,421 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "['tôi tiếp tục làm thí nghiệm này 1 thời gian',\n", - " 'và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .']" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "text_to[-2:]" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size, \n", - " from_dict_size, to_dict_size, learning_rate, \n", - " batch_size, dropout = 0.5, beam_width = 15):\n", - " \n", - " def lstm_cell(size, reuse=False):\n", - " return tf.nn.rnn_cell.GRUCell(size, reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", - " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", - " batch_size = tf.shape(self.X)[0]\n", - " # encoder\n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " for n in range(num_layers):\n", - " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", - " cell_fw = lstm_cell(size_layer // 2),\n", - " cell_bw = lstm_cell(size_layer // 2),\n", - " inputs = encoder_embedded,\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32,\n", - " scope = 'bidirectional_rnn_%d'%(n))\n", - " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", - " \n", - " bi_state = tf.concat((state_fw, state_bw), -1)\n", - " self.encoder_state = tuple([bi_state] * num_layers)\n", - " \n", - " self.encoder_state = tuple(self.encoder_state[-1] for _ in range(num_layers))\n", - " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " # decoder\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([lstm_cell(size_layer) for _ in range(num_layers)])\n", - " dense_layer = tf.layers.Dense(to_dict_size)\n", - " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", - " inputs = tf.nn.embedding_lookup(decoder_embeddings, decoder_input),\n", - " sequence_length = self.Y_seq_len,\n", - " time_major = False)\n", - " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = training_helper,\n", - " initial_state = self.encoder_state,\n", - " output_layer = dense_layer)\n", - " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = training_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", - " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", - " embedding = decoder_embeddings,\n", - " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", - " end_token = EOS)\n", - " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = predicting_helper,\n", - " initial_state = self.encoder_state,\n", - " output_layer = dense_layer)\n", - " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = predicting_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", - " self.training_logits = training_decoder_output.rnn_output\n", - " self.predicting_ids = predicting_decoder_output.sample_id\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.training_logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(len(sentence))\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 6.614276, avg accuracy: 0.050476\n", - "epoch: 2, avg loss: 6.205797, avg accuracy: 0.054426\n", - "epoch: 3, avg loss: 6.095009, avg accuracy: 0.079415\n", - "epoch: 4, avg loss: 5.981892, avg accuracy: 0.100438\n", - "epoch: 5, avg loss: 5.901337, avg accuracy: 0.109276\n", - "epoch: 6, avg loss: 5.792093, avg accuracy: 0.113754\n", - "epoch: 7, avg loss: 5.641451, avg accuracy: 0.126755\n", - "epoch: 8, avg loss: 5.470055, avg accuracy: 0.138390\n", - "epoch: 9, avg loss: 5.289564, avg accuracy: 0.149933\n", - "epoch: 10, avg loss: 5.075469, avg accuracy: 0.172347\n", - "epoch: 11, avg loss: 4.851264, avg accuracy: 0.189333\n", - "epoch: 12, avg loss: 4.627014, avg accuracy: 0.205995\n", - "epoch: 13, avg loss: 4.382761, avg accuracy: 0.229566\n", - "epoch: 14, avg loss: 4.137850, avg accuracy: 0.257346\n", - "epoch: 15, avg loss: 3.912164, avg accuracy: 0.286553\n", - "epoch: 16, avg loss: 3.698820, avg accuracy: 0.320739\n", - "epoch: 17, avg loss: 3.450189, avg accuracy: 0.356606\n", - "epoch: 18, avg loss: 3.196571, avg accuracy: 0.406529\n", - "epoch: 19, avg loss: 2.960001, avg accuracy: 0.449249\n", - "epoch: 20, avg loss: 2.760768, avg accuracy: 0.484461\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k+batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index ], PAD)\n", - " predicted, accuracy,loss, _ = sess.run([model.predicting_ids, \n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: or , if you had to choose between the last two , which one would you choose ?\n", - "REAL ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ?\n", - "PREDICTED ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? , bạn sẽ hỏi họ bạn có đau không ? , bạn sẽ hỏi họ bạn có thể làm đau đau đau đau đau đau đau đau đau đau đau đau \n", - "\n", - "row 2\n", - "QUESTION: i kept on doing this for a while .\n", - "REAL ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ?\n", - "PREDICTED ANSWER: hoặc nếu được chọn giữa 2 kiểu cuối , bạn sẽ chọn cái nào ? \n", - "\n", - "row 3\n", - "QUESTION: and then , like all good academic projects , i got more funding .\n", - "REAL ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian\n", - "PREDICTED ANSWER: và tôi tiếp tục làm thí nghiệm này 1 thời gian \n", - "\n", - "row 4\n", - "QUESTION: i moved to sounds , electrical shocks -- i even had a pain suit that i could get people to feel much more pain .\n", - "REAL ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .\n", - "PREDICTED ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/13.basic-seq2seq-luong.ipynb b/neural-machine-translation/13.basic-seq2seq-luong.ipynb index aea7d14..73e25fb 100644 --- a/neural-machine-translation/13.basic-seq2seq-luong.ipynb +++ b/neural-machine-translation/13.basic-seq2seq-luong.ipynb @@ -6,84 +6,78 @@ "metadata": {}, "outputs": [], "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '0'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, "outputs": [ { - "name": "stdout", + "name": "stderr", "output_type": "stream", "text": [ - "len from: 500, len to: 500\n" + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/usr/lib/python3/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (3.0.4) doesn't match a supported version!\n", + " RequestsDependencyWarning)\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" ] } ], "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], + "outputs": [], "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" ] }, { @@ -92,22 +86,18 @@ "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" + "dictionary.keys()" ] }, { @@ -115,6 +105,19 @@ "execution_count": 6, "metadata": {}, "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], "source": [ "GO = dictionary_from['GO']\n", "PAD = dictionary_from['PAD']\n", @@ -124,21 +127,61 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 15, "metadata": {}, "outputs": [], "source": [ - "class Chatbot:\n", + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", " def __init__(self, size_layer, num_layers, embedded_size,\n", " from_dict_size, to_dict_size, learning_rate, batch_size):\n", " \n", @@ -147,8 +190,9 @@ " \n", " self.X = tf.placeholder(tf.int32, [None, None])\n", " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", " batch_size = tf.shape(self.X)[0]\n", " \n", " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", @@ -157,27 +201,35 @@ " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " \n", - " attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n", - " memory = encoder_embedded)\n", - " rnn_cells = tf.contrib.seq2seq.AttentionWrapper(cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", - " attention_mechanism = attention_mechanism,\n", - " attention_layer_size = size_layer)\n", - " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " sequence_length=self.X_seq_len,\n", " dtype = tf.float32)\n", - " last_state = tuple(last_state[0][-1] for _ in range(num_layers))\n", " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", + " \n", + " attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n", + " memory = last_output)\n", + " rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n", + " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", + " attention_mechanism = attention_mechanism,\n", + " attention_layer_size = size_layer)\n", + " \n", + " initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = initial_state,\n", " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", " targets = self.Y,\n", " weights = masks)\n", " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", " y_t = tf.cast(y_t, tf.int32)\n", " self.prediction = tf.boolean_mask(y_t, masks)\n", " mask_label = tf.boolean_mask(self.Y, masks)\n", @@ -188,44 +240,44 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 11, "metadata": {}, "outputs": [], "source": [ - "size_layer = 256\n", + "size_layer = 512\n", "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", "epoch = 20" ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 16, "metadata": {}, "outputs": [ { - "name": "stdout", + "name": "stderr", "output_type": "stream", "text": [ - "WARNING:tensorflow:From :6: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "W0902 22:44:13.330178 139806083041088 deprecation.py:323] From :43: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", "Instructions for updating:\n", - "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n" + "Use keras.layers.dense instead.\n" ] } ], "source": [ "tf.reset_default_graph()\n", "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", " len(dictionary_to), learning_rate,batch_size)\n", "sess.run(tf.global_variables_initializer())" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 17, "metadata": {}, "outputs": [], "source": [ @@ -236,149 +288,540 @@ " for k in i.split():\n", " ints.append(dic.get(k,UNK))\n", " X.append(ints)\n", - " return X" + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 18, "metadata": {}, "outputs": [], "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 19, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [05:58<00:00, 2.91it/s, accuracy=0.0776, cost=6.88]\n", + "minibatch loop: 100%|██████████| 23/23 [00:03<00:00, 6.65it/s, accuracy=0.0904, cost=6.7] \n", + "minibatch loop: 0%| | 0/1042 [00:00 phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Nhận ta lõi ! Paul lõi Paul hứng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Nhận xứ lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Nhận lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Nhận lõi tế lõi , lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Nhận : lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Nhận xứ lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Nhận : xứ lõi Paul lõi Paul lõi Paul lõi Paul lõi Paul . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", "\n", - "row 2\n", - "QUESTION: and then always the same thing happens : people are watching each other and think , " oh , my god .\n", - "REAL ANSWER: và sau đó như thường lệ : mọi người nhìn nhau và nghĩ , " trời đất ơi "\n", - "PREDICTED ANSWER: và tôi tôi , , , , , . , , , tôi có , , , , , \n", + "8 predict: Nhận lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", "\n", - "row 3\n", - "QUESTION: a freshly waxed car , the water molecules slump to about 90 degrees .\n", - "REAL ANSWER: một xe vừa bôi sáp , những phân tử nước sụt xuống gần ̣ 90 độ .\n", - "PREDICTED ANSWER: ai , , , , , , , , một , , , của . \n", + "9 predict: Nhận : sử lõi lõi lõi , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", "\n", - "row 4\n", - "QUESTION: we 're going to do it non-invasively using mri .\n", - "REAL ANSWER: chúng ta sẽ làm điều này mà không xâm nhập bên trong , sử dụng mri .\n", - "PREDICTED ANSWER: và tôi tôi , một , , , , một của . \n", + "10 predict: Nhận lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Nhận xứ lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhận lõi lõi Paul lõi lõi lõi lõi lõi Paul . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Nhận lõi không lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Nhận : không lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Nhận : lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Nhận : thu lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Nhận xứ lõi lõi Paul lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Paul ấy tế lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Nhận xứ lõi lõi Paul lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi lõi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", "\n" ] } ], "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" ] }, { diff --git a/neural-machine-translation/14.lstm-seq2seq-luong.ipynb b/neural-machine-translation/14.lstm-seq2seq-luong.ipynb index 85f6479..383a1b4 100644 --- a/neural-machine-translation/14.lstm-seq2seq-luong.ipynb +++ b/neural-machine-translation/14.lstm-seq2seq-luong.ipynb @@ -6,84 +6,78 @@ "metadata": {}, "outputs": [], "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '1'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, "outputs": [ { - "name": "stdout", + "name": "stderr", "output_type": "stream", "text": [ - "len from: 500, len to: 500\n" + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/usr/lib/python3/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (3.0.4) doesn't match a supported version!\n", + " RequestsDependencyWarning)\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" ] } ], "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], + "outputs": [], "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" ] }, { @@ -92,22 +86,18 @@ "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" + "dictionary.keys()" ] }, { @@ -115,6 +105,19 @@ "execution_count": 6, "metadata": {}, "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], "source": [ "GO = dictionary_from['GO']\n", "PAD = dictionary_from['PAD']\n", @@ -124,32 +127,72 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, "metadata": {}, "outputs": [], "source": [ - "class Chatbot:\n", + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", " def __init__(self, size_layer, num_layers, embedded_size,\n", " from_dict_size, to_dict_size, learning_rate, batch_size):\n", " \n", " def cells(reuse=False):\n", - " return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),\n", - " reuse=reuse)\n", + " return tf.nn.rnn_cell.LSTMCell(size_layer, initializer=tf.orthogonal_initializer(),reuse=reuse)\n", " \n", " self.X = tf.placeholder(tf.int32, [None, None])\n", " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", " batch_size = tf.shape(self.X)[0]\n", " \n", " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", @@ -158,27 +201,35 @@ " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " \n", - " attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n", - " memory = encoder_embedded)\n", - " rnn_cells = tf.contrib.seq2seq.AttentionWrapper(cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", - " attention_mechanism = attention_mechanism,\n", - " attention_layer_size = size_layer)\n", - " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " sequence_length=self.X_seq_len,\n", " dtype = tf.float32)\n", - " last_state = tuple(last_state[0][-1] for _ in range(num_layers))\n", " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", + " \n", + " attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n", + " memory = last_output)\n", + " rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n", + " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", + " attention_mechanism = attention_mechanism,\n", + " attention_layer_size = size_layer)\n", + " \n", + " initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = initial_state,\n", " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", " targets = self.Y,\n", " weights = masks)\n", " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", " y_t = tf.cast(y_t, tf.int32)\n", " self.prediction = tf.boolean_mask(y_t, masks)\n", " mask_label = tf.boolean_mask(self.Y, masks)\n", @@ -189,34 +240,74 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 11, "metadata": {}, "outputs": [], "source": [ - "size_layer = 128\n", + "size_layer = 512\n", "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", "epoch = 20" ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 12, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 22:47:37.077608 140335994128192 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 22:47:37.130056 140335994128192 deprecation.py:323] From :10: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 22:47:37.132220 140335994128192 deprecation.py:323] From :25: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 22:47:37.133406 140335994128192 deprecation.py:323] From :28: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 22:47:37.550059 140335994128192 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:47:38.225967 140335994128192 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 22:47:38.831751 140335994128192 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n", + "W0902 22:47:38.836213 140335994128192 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:47:40.049757 140335994128192 deprecation.py:323] From :43: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n" + ] + } + ], "source": [ "tf.reset_default_graph()\n", "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", " len(dictionary_to), learning_rate,batch_size)\n", "sess.run(tf.global_variables_initializer())" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 13, "metadata": {}, "outputs": [], "source": [ @@ -227,149 +318,540 @@ " for k in i.split():\n", " ints.append(dic.get(k,UNK))\n", " X.append(ints)\n", - " return X" + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 15, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [08:30<00:00, 2.04it/s, accuracy=0.118, cost=6.4] \n", + "minibatch loop: 100%|██████████| 23/23 [00:04<00:00, 5.61it/s, accuracy=0.107, cost=6.16] \n", + "minibatch loop: 0%| | 0/1042 [00:00 phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là câu câu hoàn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Nó chỉ trò trò trò chơi ghép ghép hợp với với . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Để tôi kể cho về về về một . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy tượng tiên tiên đầu tiên : Một người đang đang đang đầu làm làm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Ông là một thơ , , nhà kịch , , một , , người đã đã đã đã đã đã cân cân tham gia gia quốc gia và quốc và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy dung xem về người người cư cư người nhập , , nhập , sự sự sự đời đã sự tế . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Từ từ từ đời dành bạn bạn cho anh anh anh cho anh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", "\n", - "row 2\n", - "QUESTION: people have wanted to look inside the human mind , the human brain , for thousands of years .\n", - "REAL ANSWER: con người muốn nhìn được vào bên trong ý nghĩ , não người , qua hàng ngàn năm nay ,\n", - "PREDICTED ANSWER: và tôi tôi tôi tôi tôi , , , , , , , , , , , , , . \n", + "8 predict: Anh ấy nhập vào im lặng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", "\n", - "row 3\n", - "QUESTION: a freshly waxed car , the water molecules slump to about 90 degrees .\n", - "REAL ANSWER: một xe vừa bôi sáp , những phân tử nước sụt xuống gần ̣ 90 độ .\n", - "PREDICTED ANSWER: và tôi tôi , , , , , , , , , , , , . \n", + "9 predict: Ông ta giết phá bởi bởi lịch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", "\n", - "row 4\n", - "QUESTION: made in 1939 , the film is older than most of our members ' grandparents .\n", - "REAL ANSWER: được làm vào năm 1939 , bộ phim có tuổi già hơn tuổi của hầu hết ông bà của các thành viên\n", - "PREDICTED ANSWER: và tôi tôi , , , , , , , , , , , , , , , , . . . \n", + "10 predict: Ông ta tôi tôi tôi tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi chưa bao giờ biết ấy ấy đời đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng cuộc sống của chúng ta còn hơn hơn bộ ức . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Cô tôi chưa bao tôi quên đời đời đời mình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Bản vụ của không không phép nó được được được , và bài bài học học học học học học , , , , chúng chúng , , chúng hành hành hành hành . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Mẫu theo theo theo theo một thuyền của của trong mùa mùa đầu trong mùa sớm của sớm sớm nhanh nhanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , xét , , tuổi tuổi khi cha đã đã qua đã đã hôn hôn hôn hôn hôn , chồng bé . bé . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Đối với ấy , cô vụ đã : : trốn trốn cô cô của trốn gia cô gia cô sống của tại Úc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó không thể cô cô cô cô ấy không công công công . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Vì thế , năm năm không vĩnh gợi với một kẽ trống trống , , trở trở trở trở thành một một một vết . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", "\n" ] } ], "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" ] }, { diff --git a/neural-machine-translation/15.gru-seq2seq-luong.ipynb b/neural-machine-translation/15.gru-seq2seq-luong.ipynb index 70a33e2..0ac27f5 100644 --- a/neural-machine-translation/15.gru-seq2seq-luong.ipynb +++ b/neural-machine-translation/15.gru-seq2seq-luong.ipynb @@ -6,84 +6,78 @@ "metadata": {}, "outputs": [], "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '3'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, "outputs": [ { - "name": "stdout", + "name": "stderr", "output_type": "stream", "text": [ - "len from: 500, len to: 500\n" + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/usr/lib/python3/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (3.0.4) doesn't match a supported version!\n", + " RequestsDependencyWarning)\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" ] } ], "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], + "outputs": [], "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" ] }, { @@ -92,22 +86,18 @@ "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" + "dictionary.keys()" ] }, { @@ -115,6 +105,19 @@ "execution_count": 6, "metadata": {}, "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], "source": [ "GO = dictionary_from['GO']\n", "PAD = dictionary_from['PAD']\n", @@ -124,21 +127,61 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, "metadata": {}, "outputs": [], "source": [ - "class Chatbot:\n", + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", " def __init__(self, size_layer, num_layers, embedded_size,\n", " from_dict_size, to_dict_size, learning_rate, batch_size):\n", " \n", @@ -147,8 +190,9 @@ " \n", " self.X = tf.placeholder(tf.int32, [None, None])\n", " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", " batch_size = tf.shape(self.X)[0]\n", " \n", " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", @@ -157,27 +201,35 @@ " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " \n", - " attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n", - " memory = encoder_embedded)\n", - " rnn_cells = tf.contrib.seq2seq.AttentionWrapper(cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", - " attention_mechanism = attention_mechanism,\n", - " attention_layer_size = size_layer)\n", - " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " sequence_length=self.X_seq_len,\n", " dtype = tf.float32)\n", - " last_state = tuple(last_state[0][-1] for _ in range(num_layers))\n", " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", + " \n", + " attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n", + " memory = last_output)\n", + " rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n", + " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", + " attention_mechanism = attention_mechanism,\n", + " attention_layer_size = size_layer)\n", + " \n", + " initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = initial_state,\n", " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", " targets = self.Y,\n", " weights = masks)\n", " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", " y_t = tf.cast(y_t, tf.int32)\n", " self.prediction = tf.boolean_mask(y_t, masks)\n", " mask_label = tf.boolean_mask(self.Y, masks)\n", @@ -188,34 +240,77 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 11, "metadata": {}, "outputs": [], "source": [ - "size_layer = 256\n", + "size_layer = 512\n", "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", "epoch = 20" ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 12, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 22:48:51.478257 140080831305536 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 22:48:51.540360 140080831305536 deprecation.py:323] From :10: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 22:48:51.542553 140080831305536 deprecation.py:323] From :25: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 22:48:51.543934 140080831305536 deprecation.py:323] From :28: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 22:48:51.915167 140080831305536 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:48:51.927394 140080831305536 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:564: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:48:51.943921 140080831305536 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:574: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 22:48:52.227863 140080831305536 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 22:48:52.951931 140080831305536 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n", + "W0902 22:48:54.072184 140080831305536 deprecation.py:323] From :43: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n" + ] + } + ], "source": [ "tf.reset_default_graph()\n", "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", " len(dictionary_to), learning_rate,batch_size)\n", "sess.run(tf.global_variables_initializer())" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 13, "metadata": {}, "outputs": [], "source": [ @@ -226,150 +321,548 @@ " for k in i.split():\n", " ints.append(dic.get(k,UNK))\n", " X.append(ints)\n", - " return X" + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 15, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [08:40<00:00, 2.00it/s, accuracy=0.103, cost=6.32] \n", + "minibatch loop: 100%|██████████| 23/23 [00:04<00:00, 5.59it/s, accuracy=0.0904, cost=6.03]\n", + "minibatch loop: 0%| | 0/1042 [00:00 phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây Attia không không không không . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", "\n", - "row 2\n", - "QUESTION: now imagine that you will soon be able to look inside your brain and select brain areas to do that same thing .\n", - "REAL ANSWER: bây giờ hãy tưởng tượng bạn sớm được nhìn vào bên trong não mình và được chọn vùng trên não để làm cùng một việc đó .\n", - "PREDICTED ANSWER: và tôi tôi , , bạn bạn , , , tôi tôi tôi tôi tôi tôi tôi , , , , , . . . . \n", + "2 predict: THực tôi không không . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", "\n", - "row 3\n", - "QUESTION: there have been three ways to try to impact the brain : the therapist 's couch , pills and the knife .\n", - "REAL ANSWER: có ba cách để làm ảnh hưởng đến não : giường của nhà trị liệu học , thuốc viên và con dao .\n", - "PREDICTED ANSWER: và tôi có , , , , của , của của của của của của của của của của . . . . . \n", + "3 predict: Để bạn bạn bạn bạn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", "\n", - "row 4\n", - "QUESTION: we run enormous models on supercomputers ; this is what i happen to do .\n", - "REAL ANSWER: chúng tôi chạy những mô hình khổng lồ trên siêu máy tính ; đây là công việc của tôi .\n", - "PREDICTED ANSWER: chúng tôi tôi chúng chúng tôi của của của của của của và và và tôi . . . \n", + "4 predict: Tìm Attia Attia Attia Attia Attia , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Anh Attia Attia , Attia , , , , , , , , , , , , , , , , , , , , , , , , , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Giờ không , hộp , hộp hộp hộp , hộp . hộp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Biét tôi , , , , , , , , , , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh lặng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Chúng tĩnh tĩnh tĩnh tĩnh tĩnh tĩnh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Anh ấy không không . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi không không không não não não não não . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng người người người người cốt cốt cốt cốt cốt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Tôi tôi tôi tôi tôi tôi tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Tôi tôi , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Một Attia , , , , , , , , , , , , , xứ , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Tôi cô , , cô , , , , cô , cô cô cô cô , cô cô nghèo nghèo cô cô cô . nghèo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Những , , , , , , , , , , , , , , , , , , , , , , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó không không không không không . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Tôi tôi , , , , , , , , , , , , , , , , , , , , , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", "\n" ] } ], "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { diff --git a/neural-machine-translation/2.lstm-seq2seq-manual.ipynb b/neural-machine-translation/2.lstm-seq2seq-manual.ipynb deleted file mode 100644 index ef6c4df..0000000 --- a/neural-machine-translation/2.lstm-seq2seq-manual.ipynb +++ /dev/null @@ -1,390 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(reuse=False):\n", - " return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", - " dtype = tf.float32)\n", - " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", - " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "maxlen_question = max([len(x) for x in X]) * 2\n", - "maxlen_answer = max([len(y) for y in Y]) * 2\n", - "\n", - "maxlen_question, maxlen_answer" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int, maxlen):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = maxlen\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(maxlen)\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 1.715693, avg accuracy: 0.883155\n", - "epoch: 2, avg loss: 0.814847, avg accuracy: 0.911936\n", - "epoch: 3, avg loss: 0.766373, avg accuracy: 0.912682\n", - "epoch: 4, avg loss: 0.726060, avg accuracy: 0.913045\n", - "epoch: 5, avg loss: 0.715116, avg accuracy: 0.914455\n", - "epoch: 6, avg loss: 0.716877, avg accuracy: 0.913318\n", - "epoch: 7, avg loss: 0.711519, avg accuracy: 0.913527\n", - "epoch: 8, avg loss: 0.712105, avg accuracy: 0.913155\n", - "epoch: 9, avg loss: 0.700975, avg accuracy: 0.914818\n", - "epoch: 10, avg loss: 0.695844, avg accuracy: 0.914736\n", - "epoch: 11, avg loss: 0.704287, avg accuracy: 0.913691\n", - "epoch: 12, avg loss: 0.688946, avg accuracy: 0.915609\n", - "epoch: 13, avg loss: 0.687791, avg accuracy: 0.914855\n", - "epoch: 14, avg loss: 0.679813, avg accuracy: 0.915309\n", - "epoch: 15, avg loss: 0.665267, avg accuracy: 0.916300\n", - "epoch: 16, avg loss: 0.666998, avg accuracy: 0.916055\n", - "epoch: 17, avg loss: 0.662029, avg accuracy: 0.915691\n", - "epoch: 18, avg loss: 0.648469, avg accuracy: 0.917382\n", - "epoch: 19, avg loss: 0.663604, avg accuracy: 0.914791\n", - "epoch: 20, avg loss: 0.648736, avg accuracy: 0.917009\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " X, Y = shuffle(X, Y)\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k + batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_answer)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)\n", - " predicted, accuracy, loss, _ = sess.run([tf.argmax(model.logits,2),\n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y,\n", - " model.X_seq_len:seq_x,\n", - " model.Y_seq_len:seq_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: by the time the pilot had finished , we had the names of a thousand schools that wished to join .\n", - "REAL ANSWER: ngay khi thử nghiệm kết thúc , chúng ta đã có tên của hàng ngàn trường học mong muốn được tham gia .\n", - "PREDICTED ANSWER: và tôi , , , , , . , , . , , . . . , , , , , . \n", - "\n", - "row 2\n", - "QUESTION: i 'm here to show you how something you can 't see can be so much fun to look at .\n", - "REAL ANSWER: hôm nay tôi đến đây để chỉ cho các bạn những thứ bạn không thể thấy được nhưng rất thú vị khi nhìn vào đó\n", - "PREDICTED ANSWER: và tôi , , , , , , , , , , . . . , . , , , , . . \n", - "\n", - "row 3\n", - "QUESTION: and every one of those scientists is in a research group , and every research group studies a wide variety of topics .\n", - "REAL ANSWER: mỗi một khoa học gia đều thuộc một nhóm nghiên cứu , và mỗi nhóm đều nghiên cứu rất nhiều đề tài đa dạng .\n", - "PREDICTED ANSWER: và tôi , , , , , , , , , , , , , , , , , , . . . \n", - "\n", - "row 4\n", - "QUESTION: and as a body of knowledge builds up , it will form one subsection , or one sub-subsection of an assessment like the ipcc , although we have others .\n", - "REAL ANSWER: khi một phần kiến thức dần định hình , nó sẽ tạo thành một tiểu mục , hay một tiểu-tiểu mục trong một bản kiểm định như ở ipcc , mặc dù còn có nhiều bài khác .\n", - "PREDICTED ANSWER: và tôi , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , . . . . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/2.lstm-seq2seq.ipynb b/neural-machine-translation/2.lstm-seq2seq.ipynb new file mode 100644 index 0000000..3d06607 --- /dev/null +++ b/neural-machine-translation/2.lstm-seq2seq.ipynb @@ -0,0 +1,869 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '1'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(reuse=False):\n", + " return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", + " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", + " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " sequence_length=self.X_seq_len,\n", + " dtype = tf.float32)\n", + " with tf.variable_scope(\"decoder\"):\n", + " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = last_state,\n", + " dtype = tf.float32)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 13:49:00.632232 140463285004096 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 13:49:00.699611 140463285004096 deprecation.py:323] From :10: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 13:49:00.702382 140463285004096 deprecation.py:323] From :25: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 13:49:00.703949 140463285004096 deprecation.py:323] From :28: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 13:49:01.167718 140463285004096 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 13:49:01.785326 140463285004096 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 13:49:02.052697 140463285004096 deprecation.py:323] From :35: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n", + "W0902 13:49:02.056450 140463285004096 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 13:49:03.013517 140463285004096 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [06:02<00:00, 2.87it/s, accuracy=0.0957, cost=6.75]\n", + "minibatch loop: 100%|██████████| 23/23 [00:02<00:00, 8.55it/s, accuracy=0.107, cost=6.6] \n", + "minibatch loop: 0%| | 0/1042 [00:00 nữ trên ba thế thế , , , những , , của giác cảm cảm cảm cảm cảm trong trong cảm dưỡng dưỡng dưỡng của của của sinh sinh mình sinh sinh học cô cô cô cô cô cô cô cô , bé , - bé bé bé bé đứa ở cứu ra ra ra nam năm , , , , , hơn hơn để có và có học và và hơn xa đi tâm tâm tâm tâm trung\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Giờ không phải là câu câu câu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Đó là một nhường một một câu sử . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Tôi tôi nói các một một số số . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy dung dung đầu tiên tiên tiên tiên ông ông anh đời đời đời đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Ông là một người thơ , một một người người đàn người ông người sống sống thời , đã có định định hiện ấy của mình mình đời của của . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy tượng tượng như coi di hệ hệ nước , , , , thực sự sự sự cuộc cuộc sống cuộc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Mộc qua , , suốt suốt , bạn còn giờ giờ giờ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Cậu ấy ăn ấm lặng lặng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Anh đã đã bị bị sử sử . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Là con tôi tôi tôi tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi đã bao giờ bao bao thế thế đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng cuộc sống của của ta tôi quá tôi chúng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Mẹ gái bao bao giờ tôi quên quên quên đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Mục của của tôi không phải cho nó nó , , , tôi tôi đã tôi tôi là , , tôi học , chúng , có gặp , chúng tôi tôi tôi lại . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Loài thuyền theo theo phao quả kéo ra đáy đá thuyền ở đường biển đầu đầu voi dưới voi dưới dưới . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ , , tôi đầu , cô cô tuổi tuổi một một một trong hôn hôn , cô , , bé . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Vì với , , , đã đã chiến hôn vào vào sống đời : trong , một tù đình sống và đình , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó chắc chắn cô cô ấy phải ấy cô ấy công . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau đó , câu nói , , , rằng bánh viễn viễn , , , bay ra bờ bờ để để dẫn dẫn dẫn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/3.gru-seq2seq-manual.ipynb b/neural-machine-translation/3.gru-seq2seq-manual.ipynb deleted file mode 100644 index 2322aaf..0000000 --- a/neural-machine-translation/3.gru-seq2seq-manual.ipynb +++ /dev/null @@ -1,384 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(reuse=False):\n", - " return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", - " dtype = tf.float32)\n", - " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", - " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "maxlen_question = max([len(x) for x in X]) * 2\n", - "maxlen_answer = max([len(y) for y in Y]) * 2" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int, maxlen):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = maxlen\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(maxlen)\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 1.551168, avg accuracy: 0.884691\n", - "epoch: 2, avg loss: 0.789407, avg accuracy: 0.910264\n", - "epoch: 3, avg loss: 0.734137, avg accuracy: 0.913064\n", - "epoch: 4, avg loss: 0.729298, avg accuracy: 0.913427\n", - "epoch: 5, avg loss: 0.724402, avg accuracy: 0.913400\n", - "epoch: 6, avg loss: 0.714839, avg accuracy: 0.914309\n", - "epoch: 7, avg loss: 0.716842, avg accuracy: 0.913573\n", - "epoch: 8, avg loss: 0.698991, avg accuracy: 0.915791\n", - "epoch: 9, avg loss: 0.697042, avg accuracy: 0.915373\n", - "epoch: 10, avg loss: 0.686981, avg accuracy: 0.915836\n", - "epoch: 11, avg loss: 0.690688, avg accuracy: 0.914136\n", - "epoch: 12, avg loss: 0.669089, avg accuracy: 0.917045\n", - "epoch: 13, avg loss: 0.658896, avg accuracy: 0.917655\n", - "epoch: 14, avg loss: 0.666537, avg accuracy: 0.915727\n", - "epoch: 15, avg loss: 0.657109, avg accuracy: 0.916336\n", - "epoch: 16, avg loss: 0.657437, avg accuracy: 0.916582\n", - "epoch: 17, avg loss: 0.637726, avg accuracy: 0.917873\n", - "epoch: 18, avg loss: 0.643969, avg accuracy: 0.916145\n", - "epoch: 19, avg loss: 0.619257, avg accuracy: 0.919318\n", - "epoch: 20, avg loss: 0.612224, avg accuracy: 0.920200\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " X, Y = shuffle(X, Y)\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k + batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_answer)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)\n", - " predicted, accuracy, loss, _ = sess.run([tf.argmax(model.logits,2),\n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y,\n", - " model.X_seq_len:seq_x,\n", - " model.Y_seq_len:seq_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: and as they wrote and debated , rather than seeing the films as artifacts , they began to see themselves .\n", - "REAL ANSWER: và khi chúng viết và tranh luận , hơn là thấy những bộ phim như là những tạo tác , chúng bắt đầu nhìn thấy bản thân .\n", - "PREDICTED ANSWER: và tôi tôi tôi , , , , , , và , , , , , , , , , , và và và . . . . \n", - "\n", - "row 2\n", - "QUESTION: rachel pike : the science behind a climate headline\n", - "REAL ANSWER: khoa học đằng sau một tiêu đề về khí hậu\n", - "PREDICTED ANSWER: và có là là là của của của của . . \n", - "\n", - "row 3\n", - "QUESTION: and i just couldn 't .\n", - "REAL ANSWER: nhưng tôi cứ không thể dừng được .\n", - "PREDICTED ANSWER: và tôi tôi tôi tôi tôi . . \n", - "\n", - "row 4\n", - "QUESTION: that report was written by 620 scientists from 40 countries .\n", - "REAL ANSWER: nghiên cứu được viết bởi 620 nhà khoa học từ 40 quốc gia khác nhau .\n", - "PREDICTED ANSWER: và có là là là là , , của của của của . . . . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/3.gru-seq2seq.ipynb b/neural-machine-translation/3.gru-seq2seq.ipynb new file mode 100644 index 0000000..bc2f0c4 --- /dev/null +++ b/neural-machine-translation/3.gru-seq2seq.ipynb @@ -0,0 +1,879 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '2'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(reuse=False):\n", + " return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", + " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", + " rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n", + " sequence_length=self.X_seq_len,\n", + " dtype = tf.float32)\n", + " with tf.variable_scope(\"decoder\"):\n", + " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = last_state,\n", + " dtype = tf.float32)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 10:35:02.010806 139636772824896 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 10:35:02.057063 139636772824896 deprecation.py:323] From :10: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 10:35:02.058954 139636772824896 deprecation.py:323] From :25: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 10:35:02.060249 139636772824896 deprecation.py:323] From :28: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 10:35:02.491889 139636772824896 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 10:35:02.501817 139636772824896 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:564: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 10:35:02.515000 139636772824896 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:574: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 10:35:02.748422 139636772824896 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 10:35:02.950766 139636772824896 deprecation.py:323] From :35: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n", + "W0902 10:35:03.903399 139636772824896 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [06:32<00:00, 2.65it/s, accuracy=0.0983, cost=6.53]\n", + "minibatch loop: 100%|██████████| 23/23 [00:02<00:00, 8.07it/s, accuracy=0.096, cost=6.29]\n", + "minibatch loop: 0%| | 0/1042 [00:00 khoảng khoảng những của nữ nữ phụ ngày hệ , bao cách về về mập mập cảm sống những trong trong trong trong sống sống sống sống sống sống sống sống sống sống với sống sống và , ở sống ở ở ở ở ở đêm đêm đêm ở ở ở ở ở ở ở ở ở ở ở ở năm năm , sống sống sống sống sống ở ở , và và và vùng , , sống sống sống ở ở ở ở này này với\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là là một chuyện . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Nó là một kết một đoạn gắn kết kết . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Hãy tôi nói cho các về một số . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hình tượng tượng dung dung : một đàn con ông ông đời đời đời đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Ông là là ngôi ngôi , ngôi người , cầm một một đàn cầm người người ước ước ước và và mọi mọi người nhà nhà thợ thợ và và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy tưởng ông ta rô chất chất đối , , , phong thực thực sự sự sự sự ông lương lương . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Từ , , với thưa thưa anh anh bè anh anh anh anh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh im đến vào . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Ông ta qua lịch lịch lịch lịch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Ông ấy là tôi ông tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi bao bao tôi đã bao trong đời đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng bộ sống của chúng ta rất hơn hơn hơn ức . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Mẹ tôi bao giờ giờ giờ giờ giờ đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Tôi của tôi là chúng đã để để , để để để , , tôi , tôi không để để hát sử sinh , , , , tôi phải phải phải chúng tôi tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Tiếp kế theo theo theo là là chìm chìm chìm chìm ẩm để để ẩm lên tránh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , lúc lúc lúc tuổi lúc tôi tôi được trong - , ở hai một xã , , , , , , , con . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Mắt sống sống đình sống sống sống thân thân thân một một cuộc sống đời đời cuộc cuộc cuộc và và cuộc cuộc và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Với đó bà bà ấy cho của công giành . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau một , năm năm , , hình , , , , là đặt đặt bờ lên khỏi biển nước nước nước biển hành . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/4.basic-seq2seq-api-greedy.ipynb b/neural-machine-translation/4.basic-seq2seq-api-greedy.ipynb deleted file mode 100644 index b5eddf1..0000000 --- a/neural-machine-translation/4.basic-seq2seq-api-greedy.ipynb +++ /dev/null @@ -1,409 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(reuse=False):\n", - " return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", - " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " \n", - " _, encoder_state = tf.nn.dynamic_rnn(\n", - " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", - " inputs = tf.nn.embedding_lookup(encoder_embedding, self.X),\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32)\n", - " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " dense = tf.layers.Dense(to_dict_size)\n", - " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " \n", - " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", - " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", - " sequence_length = self.Y_seq_len,\n", - " time_major = False)\n", - " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = training_helper,\n", - " initial_state = encoder_state,\n", - " output_layer = dense)\n", - " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = training_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", - " self.training_logits = training_decoder_output.rnn_output\n", - " \n", - " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", - " embedding = decoder_embedding,\n", - " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", - " end_token = EOS)\n", - " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = predicting_helper,\n", - " initial_state = encoder_state,\n", - " output_layer = dense)\n", - " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = predicting_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", - " self.predicting_ids = predicting_decoder_output.sample_id\n", - " \n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.training_logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "WARNING:tensorflow:From :6: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", - "Instructions for updating:\n", - "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n" - ] - } - ], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(len(sentence))\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 6.639511, avg accuracy: 0.061922\n", - "epoch: 2, avg loss: 5.879192, avg accuracy: 0.102900\n", - "epoch: 3, avg loss: 5.572026, avg accuracy: 0.130366\n", - "epoch: 4, avg loss: 5.232392, avg accuracy: 0.152376\n", - "epoch: 5, avg loss: 4.865276, avg accuracy: 0.188383\n", - "epoch: 6, avg loss: 4.470282, avg accuracy: 0.234282\n", - "epoch: 7, avg loss: 4.052670, avg accuracy: 0.287898\n", - "epoch: 8, avg loss: 3.640871, avg accuracy: 0.354405\n", - "epoch: 9, avg loss: 3.249600, avg accuracy: 0.421314\n", - "epoch: 10, avg loss: 2.895601, avg accuracy: 0.487875\n", - "epoch: 11, avg loss: 2.601654, avg accuracy: 0.542940\n", - "epoch: 12, avg loss: 2.318833, avg accuracy: 0.599123\n", - "epoch: 13, avg loss: 2.023742, avg accuracy: 0.663397\n", - "epoch: 14, avg loss: 1.755580, avg accuracy: 0.723884\n", - "epoch: 15, avg loss: 1.522422, avg accuracy: 0.777484\n", - "epoch: 16, avg loss: 1.317238, avg accuracy: 0.815015\n", - "epoch: 17, avg loss: 1.125093, avg accuracy: 0.853098\n", - "epoch: 18, avg loss: 0.933701, avg accuracy: 0.893458\n", - "epoch: 19, avg loss: 0.757271, avg accuracy: 0.931947\n", - "epoch: 20, avg loss: 0.605072, avg accuracy: 0.960998\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k+batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index ], PAD)\n", - " predicted, accuracy,loss, _ = sess.run([model.predicting_ids, \n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: or , if you had to choose between the last two , which one would you choose ?\n", - "REAL ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ?\n", - "PREDICTED ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ? \n", - "\n", - "row 2\n", - "QUESTION: i kept on doing this for a while .\n", - "REAL ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ?\n", - "PREDICTED ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ? \n", - "\n", - "row 3\n", - "QUESTION: and then , like all good academic projects , i got more funding .\n", - "REAL ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian\n", - "PREDICTED ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian \n", - "\n", - "row 4\n", - "QUESTION: i moved to sounds , electrical shocks -- i even had a pain suit that i could get people to feel much more pain .\n", - "REAL ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .\n", - "PREDICTED ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/4.basic-seq2seq-contrib-greedy.ipynb b/neural-machine-translation/4.basic-seq2seq-contrib-greedy.ipynb new file mode 100644 index 0000000..bc467f9 --- /dev/null +++ b/neural-machine-translation/4.basic-seq2seq-contrib-greedy.ipynb @@ -0,0 +1,894 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '3'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(reuse=False):\n", + " return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " \n", + " _, encoder_state = tf.nn.dynamic_rnn(\n", + " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", + " inputs = tf.nn.embedding_lookup(encoder_embedding, self.X),\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32)\n", + " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " dense = tf.layers.Dense(to_dict_size)\n", + " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " \n", + " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", + " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", + " sequence_length = self.Y_seq_len,\n", + " time_major = False)\n", + " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = training_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = training_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", + " self.training_logits = training_decoder_output.rnn_output\n", + " \n", + " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", + " embedding = decoder_embedding,\n", + " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", + " end_token = EOS)\n", + " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = predicting_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = predicting_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", + " self.predicting_ids = predicting_decoder_output.sample_id\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 10:37:50.396917 139850844325696 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 10:37:50.430243 139850844325696 deprecation.py:323] From :10: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 10:37:50.431915 139850844325696 deprecation.py:323] From :22: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 10:37:50.436314 139850844325696 deprecation.py:323] From :25: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 10:37:50.877376 139850844325696 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 10:37:50.889265 139850844325696 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:459: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 10:37:51.034368 139850844325696 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 10:37:51.763631 139850844325696 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [05:37<00:00, 3.09it/s, accuracy=0.118, cost=5.76] \n", + "minibatch loop: 100%|██████████| 23/23 [00:03<00:00, 6.70it/s, accuracy=0.175, cost=5.27]\n", + "minibatch loop: 0%| | 0/1042 [00:00 phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Nhưng tôi đã nghĩ , tôi đã nói rằng , \" Nghe này , tôi đã gặp một người phụ nữ , tôi đã gặp nhau . \" Tôi đã nói với tôi rằng Meg Ryan không phải là một người đàn ông . \" Tôi nghĩ rằng đó là một câu chuyện . Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Nhưng tôi đã nghĩ , tôi đã nói rằng , \" Nghe này , tôi đã gặp một người phụ nữ , tôi đã gặp nhau . \" Tôi đã nói với tôi rằng Meg Ryan không phải là một người đàn ông . \" Tôi nghĩ rằng đó là một câu chuyện . Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Chúng ta có thể làm gì ? \" \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Chúng ta có thể làm được điều này . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \"\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Chúng ta có thể làm được điều này . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Chúng ta có thể làm gì ? \" \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Tôi đã gặp nhiều người ở đây , tôi đã gặp nhau . Tôi đã làm việc với một nhóm người . Và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình ,\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Tôi đã gặp nhiều người ở đây , tôi đã gặp nhau . Tôi đã làm việc với một nhóm người . Và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình ,\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Tôi đã gặp nhiều người ở đây , tôi đã gặp nhau . Tôi đã làm việc với một nhóm người . Và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình ,\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi đã gặp nhiều người ở đây , tôi đã gặp nhau . Tôi đã làm việc với một nhóm người . Và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình ,\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng tôi đã nghĩ , tôi đã nói rằng , \" Nghe này , tôi đã gặp một người phụ nữ , tôi đã gặp nhau . \" Tôi đã nói với tôi rằng Meg Ryan không phải là một người đàn ông . \" Tôi nghĩ rằng đó là một câu chuyện . Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Nhưng tôi đã nghĩ , tôi đã nói rằng , \" Nghe này , tôi đã gặp một người phụ nữ , tôi đã gặp nhau . \" Tôi đã nói với tôi rằng Meg Ryan không phải là một người đàn ông . \" Tôi nghĩ rằng đó là một câu chuyện . Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Nhưng tôi đã nghĩ , tôi đã nói rằng , \" Nghe này , tôi đã gặp một người phụ nữ , tôi đã gặp nhau . \" Tôi đã nói với tôi rằng Meg Ryan không phải là một người đàn ông . \" Tôi nghĩ rằng đó là một câu chuyện . Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \"\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Nhưng tôi đã nghĩ , tôi đã nói rằng , \" Nghe này , tôi đã gặp một người phụ nữ , tôi đã gặp nhau . \" Tôi đã nói với tôi rằng Meg Ryan không phải là một người đàn ông . \" Tôi nghĩ rằng đó là một câu chuyện . Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Tôi đã gặp nhiều người ở đây , tôi đã gặp nhau . Tôi đã làm việc với một nhóm người . Và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình , và tôi đã làm việc cùng với đội của mình ,\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nhưng tôi đã nghĩ , tôi đã nói rằng , \" Nghe này , tôi đã gặp một người phụ nữ , tôi đã gặp nhau . \" Tôi đã nói với tôi rằng Meg Ryan không phải là một người đàn ông . \" Tôi nghĩ rằng đó là một câu chuyện . Tôi đã làm việc với tôi . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Chúng ta có thể làm gì ? \" \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết . \" Tôi không biết .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/5.lstm-seq2seq-api-greedy.ipynb b/neural-machine-translation/5.lstm-seq2seq-api-greedy.ipynb deleted file mode 100644 index 38fa81e..0000000 --- a/neural-machine-translation/5.lstm-seq2seq-api-greedy.ipynb +++ /dev/null @@ -1,392 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(reuse=False):\n", - " return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", - " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " \n", - " _, encoder_state = tf.nn.dynamic_rnn(\n", - " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", - " inputs = tf.nn.embedding_lookup(encoder_embedding, self.X),\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32)\n", - " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " dense = tf.layers.Dense(to_dict_size)\n", - " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " \n", - " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", - " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", - " sequence_length = self.Y_seq_len,\n", - " time_major = False)\n", - " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = training_helper,\n", - " initial_state = encoder_state,\n", - " output_layer = dense)\n", - " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = training_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", - " self.training_logits = training_decoder_output.rnn_output\n", - " \n", - " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", - " embedding = decoder_embedding,\n", - " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", - " end_token = EOS)\n", - " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = predicting_helper,\n", - " initial_state = encoder_state,\n", - " output_layer = dense)\n", - " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = predicting_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", - " self.predicting_ids = predicting_decoder_output.sample_id\n", - " \n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.training_logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(len(sentence))\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 6.607375, avg accuracy: 0.049102\n", - "epoch: 2, avg loss: 6.104367, avg accuracy: 0.075862\n", - "epoch: 3, avg loss: 5.976006, avg accuracy: 0.091874\n", - "epoch: 4, avg loss: 5.886806, avg accuracy: 0.111627\n", - "epoch: 5, avg loss: 5.832548, avg accuracy: 0.111744\n", - "epoch: 6, avg loss: 5.772666, avg accuracy: 0.118138\n", - "epoch: 7, avg loss: 5.705306, avg accuracy: 0.121704\n", - "epoch: 8, avg loss: 5.622493, avg accuracy: 0.125727\n", - "epoch: 9, avg loss: 5.525803, avg accuracy: 0.134204\n", - "epoch: 10, avg loss: 5.425576, avg accuracy: 0.141575\n", - "epoch: 11, avg loss: 5.325510, avg accuracy: 0.143837\n", - "epoch: 12, avg loss: 5.228832, avg accuracy: 0.148775\n", - "epoch: 13, avg loss: 5.132649, avg accuracy: 0.154584\n", - "epoch: 14, avg loss: 5.047837, avg accuracy: 0.160110\n", - "epoch: 15, avg loss: 4.950598, avg accuracy: 0.165813\n", - "epoch: 16, avg loss: 4.857364, avg accuracy: 0.172679\n", - "epoch: 17, avg loss: 4.766294, avg accuracy: 0.178798\n", - "epoch: 18, avg loss: 4.682445, avg accuracy: 0.188729\n", - "epoch: 19, avg loss: 4.601195, avg accuracy: 0.195077\n", - "epoch: 20, avg loss: 4.520952, avg accuracy: 0.202590\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k+batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index ], PAD)\n", - " predicted, accuracy,loss, _ = sess.run([model.predicting_ids, \n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: or , if you had to choose between the last two , which one would you choose ?\n", - "REAL ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ?\n", - "PREDICTED ANSWER: và một người , tôi là một người , và bạn có thể là một người , và bạn có thể ? \n", - "\n", - "row 2\n", - "QUESTION: i kept on doing this for a while .\n", - "REAL ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ?\n", - "PREDICTED ANSWER: nhưng tôi có thể làm , tôi sẽ làm thế nào ? \n", - "\n", - "row 3\n", - "QUESTION: and then , like all good academic projects , i got more funding .\n", - "REAL ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian\n", - "PREDICTED ANSWER: và tôi sẽ làm tôi , bạn sẽ làm thế nào ? \n", - "\n", - "row 4\n", - "QUESTION: i moved to sounds , electrical shocks -- i even had a pain suit that i could get people to feel much more pain .\n", - "REAL ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .\n", - "PREDICTED ANSWER: và tôi có thể làm , tôi sẽ làm thế một người , và bạn có thể làm thế một người . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/5.lstm-seq2seq-contrib-greedy.ipynb b/neural-machine-translation/5.lstm-seq2seq-contrib-greedy.ipynb new file mode 100644 index 0000000..80d8806 --- /dev/null +++ b/neural-machine-translation/5.lstm-seq2seq-contrib-greedy.ipynb @@ -0,0 +1,894 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '0'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(reuse=False):\n", + " return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " \n", + " _, encoder_state = tf.nn.dynamic_rnn(\n", + " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", + " inputs = tf.nn.embedding_lookup(encoder_embedding, self.X),\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32)\n", + " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " dense = tf.layers.Dense(to_dict_size)\n", + " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " \n", + " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", + " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", + " sequence_length = self.Y_seq_len,\n", + " time_major = False)\n", + " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = training_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = training_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", + " self.training_logits = training_decoder_output.rnn_output\n", + " \n", + " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", + " embedding = decoder_embedding,\n", + " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", + " end_token = EOS)\n", + " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = predicting_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = predicting_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", + " self.predicting_ids = predicting_decoder_output.sample_id\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 14:02:30.343306 140044124321600 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 14:02:30.374736 140044124321600 deprecation.py:323] From :10: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 14:02:30.376574 140044124321600 deprecation.py:323] From :22: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 14:02:30.381024 140044124321600 deprecation.py:323] From :25: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 14:02:30.787908 140044124321600 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 14:02:31.391328 140044124321600 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 14:02:32.102221 140044124321600 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n", + "W0902 14:02:32.415893 140044124321600 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [07:27<00:00, 2.33it/s, accuracy=0.141, cost=5.68]\n", + "minibatch loop: 100%|██████████| 23/23 [00:03<00:00, 6.05it/s, accuracy=0.198, cost=5.26]\n", + "minibatch loop: 0%| | 0/1042 [00:00 năm nay , sống trong một thế giới gồm người phụ nữ trong tương lai , khoảng tháng tuổi , người phụ nữ sống ở quê hương và sinh sản , cô ấy đang ở trong một khoảng thời gian riêng rẽ , và cô ấy đang ở trong một cuộc sống của cô ấy , và hỏi cô ấy , trong khi không có con trai nào , chị sống trên đời sống của cô ấy và cho cô ấy đi về làng của chị ? - - hôm nay chị chị chị sẽ làm cái này ? SS hôm nay ? \" Xin chào đón chúng vào tháng nay ? \" và cô ấy đang làm gì ? \" và chị chị này ? \" - - phòng này đã làm được điều này ? \" Xin chào đời mình ? \" - cô ấy đã làm vậy ? \" Xin chào đời mình ? \" - cô ấy sẽ làm điều này ? \" và chị đã làm thế này ? \" Xin chào ? \" - - & gt\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là câu chuyện đầy kịch bản . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Đó là bài tập mà người ta quan tâm đến . . . . . . . . . . . . . . . . . . . . . . . theo nhiều cách khác . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . theo quan điểm đó . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Để tôi kể các bạn nghe một vài tấm hình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Tưởng tượng thử xem một cuộc phỏng vấn của một người đàn ông bước vào cuộc hành trình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" . . . \" và nó làm việc của nó . \" . . . \" . . . \" làm thế nào . \" . \" . \" . \" . \" . \" . \" . \" . . . \" . \" . \"\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Một nhà triết học , một nhà triết học vĩ đại , một người đàn ông đã chứng kiến sự thiếu hụt của chính mình và chính trị gia tăng trưởng của chính mình . và là một phần của sự tự do của chính mình . . . . . . . . và cả của chính mình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" . . . \" của tôi . \" . . . \" của chính mình . \" của họ . \" . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy tưởng tượng rằng chính phủ Trung Quốc bị xâm nhập vào quân đội luôn luôn luôn là một cuộc đời thật tuyệt vời . luôn luôn tự hào về nó . . . . . . . . luôn luôn là một phần của cuộc đời thực sự . . . . . . luôn luôn tự hào về nó . . . . . . . . . . . . . . . luôn luôn tự hào về nó . . . . . . . . . . . . . . . . . . . luôn luôn tự hào về điều đó . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . luôn luôn tự hào hứng . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Với từ điển , anh di chuyển anh khác , anh ấy đã gặp anh ấy . . . . và anh chị . . . . . . . . . . . . . . . . . . . . . . . và anh ấy đã cống hiến . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . và anh ấy cống hiến . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . anh đã làm anh ấy cống hiến . . . và\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh ta đã bước vào quá trình dập cự . Đủ rồi . Đủ rồi . Đủ rồi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . nhiên độ dài cả . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . nhiên đó . . . . . . . . . . nhiên sự thiếu trọng lực . \" Đủ rồi . . . . . . . . . . . . . . . . . . . . . . . . nhiên sự giận dữ . \" - i nảy mầm . \" cùng nhau . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Ông đã chết vì lịch sử lâu đời nhất . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Ông ấy là anh trai tôi . anh ấy chia sẻ anh ấy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi chưa bao giờ sống trong đời . Thật không sống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng chúng ta sống thiên nhiên hơn về mặt lịch sử ban đầu của chúng ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ta càng tự hào ngôn ngữ . \" . . . ta miêu tả ngôn ngữ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Tôi không bao giờ nhắc lại cuộc đời mình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Giải pháp của chúng ta đã sẵn sàng không để chữa trị cho bệnh nhân và sẵn sàng để nó , mà vẫn còn đó , rằng chúng ta đã cố gắng lờ đi . Theo ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Tiếp theo của High Line bắt đầu chú tàu Titanic vào tảng băng nhô lên của vũ trụ lần nữa . . . . . . . . . . từ tàu Titanic . Bang . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . nhiều không gian nổi bật lên tới ban đêm . . . . nhiều ánh sáng mặt trời sẽ đi đến bờ kỳ cách đây . . . . nhiều hướng tới ánh sáng . . . . . . . . . . . . . . . . . . nhiều hướng đến bờ biển . . . . . . . . . . . . . . . . . . . nhiên qua ánh sáng . ánh sáng nói . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , tuổi trưởng thành , người phụ nữ khi cưới ba tuổi , bà đã nhận được câu lạc bộ . Câu chuyện của cô ấy . . . . . . . . . . . . . . bà ấy đã kết hôn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cô ấy đã nhận được một câu lạc bộ đặc biệt này . . . . . . . . Cô ấy nhận được một ý niệm về cô ấy . . . . . Cô ấy nhận được một ý tưởng nhỏ nhặt về đời mình . . . . . . . . . . Cô ấy nhận được một ý tưởng nhỏ nhặt . sau đó . . . . . và cô ấy nhận được ý kiến nhỏ . sau đấy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Trong đời , sống của đời sống tự hào đã sống trong đời : cứu sống gia đình và gia đình đời sống một cuộc sống mới đời sống sót . Vô danh lịch sử \" . \" và gia đình đã sống . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . và kể cả cuộc đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời mới đời . \" . . . \" . . . \" . . . \" . . . \" . . \" . \" . \" . \" . \" . \"\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó gần đến với cô ấy trong cơ thể cô ấy không thành công . . . . . . . . . . . . . . . \" ấy đã là một cơ hội cơ bản . \" . \" . \" . . . \" ấy đã dành cả đời mình . \" . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" . . . \" một cơ quan này . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \" . \"\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau một trăm con tàu Titanic , một con tàu không bắt hái lượm , đâm vào một tàu thuỷ tinh cao tới tàu Apollo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/6.gru-seq2seq-contrib-greedy.ipynb b/neural-machine-translation/6.gru-seq2seq-contrib-greedy.ipynb new file mode 100644 index 0000000..b7344e9 --- /dev/null +++ b/neural-machine-translation/6.gru-seq2seq-contrib-greedy.ipynb @@ -0,0 +1,890 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '2'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(reuse=False):\n", + " return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " \n", + " _, encoder_state = tf.nn.dynamic_rnn(\n", + " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", + " inputs = tf.nn.embedding_lookup(encoder_embedding, self.X),\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32)\n", + " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " dense = tf.layers.Dense(to_dict_size)\n", + " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", + " \n", + " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", + " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", + " sequence_length = self.Y_seq_len,\n", + " time_major = False)\n", + " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = training_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = training_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", + " self.training_logits = training_decoder_output.rnn_output\n", + " \n", + " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", + " embedding = decoder_embedding,\n", + " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", + " end_token = EOS)\n", + " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", + " cell = decoder_cells,\n", + " helper = predicting_helper,\n", + " initial_state = encoder_state,\n", + " output_layer = dense)\n", + " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", + " decoder = predicting_decoder,\n", + " impute_finished = True,\n", + " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", + " self.predicting_ids = predicting_decoder_output.sample_id\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 13:51:37.402034 140257314834240 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 13:51:37.434925 140257314834240 deprecation.py:323] From :10: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 13:51:37.437036 140257314834240 deprecation.py:323] From :22: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 13:51:37.441887 140257314834240 deprecation.py:323] From :25: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 13:51:37.872842 140257314834240 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 13:51:37.883050 140257314834240 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:564: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 13:51:37.896491 140257314834240 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:574: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 13:51:38.124455 140257314834240 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 13:51:38.820707 140257314834240 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [07:23<00:00, 2.35it/s, accuracy=0.202, cost=5.19]\n", + "minibatch loop: 100%|██████████| 23/23 [00:03<00:00, 6.02it/s, accuracy=0.237, cost=4.86]\n", + "minibatch loop: 0%| | 0/1042 [00:00 phút trong mỗi ngày so sánh phụ nữ , phụ nữ không bao giờ có thể già hơn tuổi trong giờ đồng hồ ngày xưa tuổi . Cô phụ nữ đã trải qua mạng lưới tiểu đường ? Cô bé chia sẻ với cô ấy và không ? Trong bài nói chuyện này , cô ấy đã truyền thông cho cô ấy như thế này - - và vì vậy cô đã làm những phụ nữ và trường hợp trong ngày hôm đó . . . . và cô bé khác . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là câu chuyện hoàn toàn khác . Đó là một câu chuyện . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Một câu đố chống lại chính thức vẫn là xong . \" cùng nhau . \" . . . cùng nhau . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Tôi nói với các bạn về một số phần . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy bắt đầu cuộc đời ông ấy : chu kỳ người đàn ông . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Anh ấy là một nhà tài ông , một trong những thời gian vừa thực sự là cuộc sống của riêng mình , anh chị và cả cuộc đấu tranh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Tưởng tượng ông ta nghĩ anh ta là người thực sự thích nghi với cuộc đời của ông ấy . Tôi thực sự tin rằng sự tiến bộ của một sự hối lộ . Mỗi trạng thái rất cứng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Nào , ngồi trong câu chuyện của anh , anh ta . Chúng ở đó . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh ta đang ngủ lặng khổ . \" Cuộc phiêu cuồng thật sự . \" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Anh ấy đã bị lịch sử bởi một lịch sử . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Đây là bố của tôi . Chấm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . là đăng ký . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi chưa biết trong đời . Thực sự là cuộc sống của một cuộc sống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng cuộc sống còn lại hơn cả đời . . của chúng ta . . . của lòng can hoan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Con người không tước mất tôi . \" - - vì bà có thể cứu sống cuộc đời của tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Sự kiện không nhất dạy học để học và làm được điều đó , nhưng chúng tôi thực sự nỗ lực qua hết , đó chính là lỗi . Vô hại . \" của chúng tôi . \" Hôm nay . \" của chúng tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Tác phẩm của thủ thư đứng thẳng đến sân khấu là một tảng băng để khoe mát vải bên trong từng ống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , trốn , khi chị gái tuổi , chị gái của gái , chị gái nhỏ bé gái , có một người chị gái nhỏ bé . Và đó chỉ có tuổi . \" Bà mơ tuổi . . . . . . . . . có nghĩa là chị bé . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Trong cuộc sống của cô chị , chồng cô ấy một cuộc sống trong một căn hộ giữa nam và nữ . . . . . . . . . . . . . . . . trong một căn đông ở giữa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó không xảy ra với cô ấy là không thành công . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau khi D , một chiếc tàu chở biển , tàu tàu lượn màu xanh vẫn còn di chuyển xa hơn . . . . . . . . . . . . một vòng một vòng quay trở lại . . . để đặt một câu hỏi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/6.gru-seq2seq-greedy.ipynb b/neural-machine-translation/6.gru-seq2seq-greedy.ipynb deleted file mode 100644 index ce0a5d2..0000000 --- a/neural-machine-translation/6.gru-seq2seq-greedy.ipynb +++ /dev/null @@ -1,392 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(reuse=False):\n", - " return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n", - " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " \n", - " _, encoder_state = tf.nn.dynamic_rnn(\n", - " cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n", - " inputs = tf.nn.embedding_lookup(encoder_embedding, self.X),\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32)\n", - " main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " dense = tf.layers.Dense(to_dict_size)\n", - " decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n", - " \n", - " training_helper = tf.contrib.seq2seq.TrainingHelper(\n", - " inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),\n", - " sequence_length = self.Y_seq_len,\n", - " time_major = False)\n", - " training_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = training_helper,\n", - " initial_state = encoder_state,\n", - " output_layer = dense)\n", - " training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = training_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = tf.reduce_max(self.Y_seq_len))\n", - " self.training_logits = training_decoder_output.rnn_output\n", - " \n", - " predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n", - " embedding = decoder_embedding,\n", - " start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n", - " end_token = EOS)\n", - " predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n", - " cell = decoder_cells,\n", - " helper = predicting_helper,\n", - " initial_state = encoder_state,\n", - " output_layer = dense)\n", - " predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n", - " decoder = predicting_decoder,\n", - " impute_finished = True,\n", - " maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n", - " self.predicting_ids = predicting_decoder_output.sample_id\n", - " \n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.training_logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(len(sentence))\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 6.595950, avg accuracy: 0.050108\n", - "epoch: 2, avg loss: 6.199383, avg accuracy: 0.060167\n", - "epoch: 3, avg loss: 6.084990, avg accuracy: 0.083561\n", - "epoch: 4, avg loss: 5.962430, avg accuracy: 0.097788\n", - "epoch: 5, avg loss: 5.888171, avg accuracy: 0.108525\n", - "epoch: 6, avg loss: 5.832853, avg accuracy: 0.114980\n", - "epoch: 7, avg loss: 5.758645, avg accuracy: 0.119347\n", - "epoch: 8, avg loss: 5.639997, avg accuracy: 0.127720\n", - "epoch: 9, avg loss: 5.506897, avg accuracy: 0.134039\n", - "epoch: 10, avg loss: 5.339745, avg accuracy: 0.146608\n", - "epoch: 11, avg loss: 5.130958, avg accuracy: 0.158601\n", - "epoch: 12, avg loss: 4.904993, avg accuracy: 0.176436\n", - "epoch: 13, avg loss: 4.674516, avg accuracy: 0.194624\n", - "epoch: 14, avg loss: 4.484314, avg accuracy: 0.215770\n", - "epoch: 15, avg loss: 4.271039, avg accuracy: 0.236365\n", - "epoch: 16, avg loss: 4.063129, avg accuracy: 0.258189\n", - "epoch: 17, avg loss: 3.863059, avg accuracy: 0.291242\n", - "epoch: 18, avg loss: 3.630035, avg accuracy: 0.326530\n", - "epoch: 19, avg loss: 3.402997, avg accuracy: 0.364216\n", - "epoch: 20, avg loss: 3.211018, avg accuracy: 0.408099\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k+batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index ], PAD)\n", - " predicted, accuracy,loss, _ = sess.run([model.predicting_ids, \n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: or , if you had to choose between the last two , which one would you choose ?\n", - "REAL ANSWER: sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ bạn có đau không ? đau như thế nào ?\n", - "PREDICTED ANSWER: sau khi thôi không làm đau mọi người nữa , bạn sẽ hỏi bạn sẽ hỏi bạn không ? \n", - "\n", - "row 2\n", - "QUESTION: i kept on doing this for a while .\n", - "REAL ANSWER: hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ?\n", - "PREDICTED ANSWER: hoặc nếu tôi chọn giữa 2 kiểu cuối , bạn sẽ chọn cái nào ? \n", - "\n", - "row 3\n", - "QUESTION: and then , like all good academic projects , i got more funding .\n", - "REAL ANSWER: tôi tiếp tục làm thí nghiệm này 1 thời gian\n", - "PREDICTED ANSWER: và tôi tiếp tục làm thí nghiệm này 1 thời gian \n", - "\n", - "row 4\n", - "QUESTION: i moved to sounds , electrical shocks -- i even had a pain suit that i could get people to feel much more pain .\n", - "REAL ANSWER: và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .\n", - "PREDICTED ANSWER: và sau đó , tôi có thể lúc đó , tôi nhận thêm nguồn tài trợ . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/7.basic-birnn-seq2seq-manual.ipynb b/neural-machine-translation/7.basic-birnn-seq2seq-manual.ipynb deleted file mode 100644 index e23de84..0000000 --- a/neural-machine-translation/7.basic-birnn-seq2seq-manual.ipynb +++ /dev/null @@ -1,412 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(size,reuse=False):\n", - " return tf.nn.rnn_cell.BasicRNNCell(size,reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " \n", - " for n in range(num_layers):\n", - " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", - " cell_fw = cells(size_layer // 2),\n", - " cell_bw = cells(size_layer // 2),\n", - " inputs = encoder_embedded,\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32,\n", - " scope = 'bidirectional_rnn_%d'%(n))\n", - " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", - "\n", - " bi_state = tf.concat((state_fw,state_bw), -1)\n", - " last_state = tuple([bi_state] * num_layers)\n", - " \n", - " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", - " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", - "\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n", - " " - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "WARNING:tensorflow:From :6: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", - "Instructions for updating:\n", - "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n" - ] - } - ], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "maxlen_question = max([len(x) for x in X]) * 2\n", - "maxlen_answer = max([len(y) for y in Y]) * 2\n", - "maxlen_question, maxlen_answer" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int, maxlen):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = maxlen\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(maxlen)\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 1.711091, avg accuracy: 0.881564\n", - "epoch: 2, avg loss: 0.864222, avg accuracy: 0.911636\n", - "epoch: 3, avg loss: 0.783447, avg accuracy: 0.913009\n", - "epoch: 4, avg loss: 0.752106, avg accuracy: 0.911964\n", - "epoch: 5, avg loss: 0.729447, avg accuracy: 0.913945\n", - "epoch: 6, avg loss: 0.724528, avg accuracy: 0.915882\n", - "epoch: 7, avg loss: 0.749808, avg accuracy: 0.913755\n", - "epoch: 8, avg loss: 0.721614, avg accuracy: 0.914509\n", - "epoch: 9, avg loss: 0.725813, avg accuracy: 0.912709\n", - "epoch: 10, avg loss: 0.731039, avg accuracy: 0.912827\n", - "epoch: 11, avg loss: 0.697485, avg accuracy: 0.915909\n", - "epoch: 12, avg loss: 0.710194, avg accuracy: 0.914564\n", - "epoch: 13, avg loss: 0.694111, avg accuracy: 0.915436\n", - "epoch: 14, avg loss: 0.690663, avg accuracy: 0.915491\n", - "epoch: 15, avg loss: 0.678798, avg accuracy: 0.916791\n", - "epoch: 16, avg loss: 0.666149, avg accuracy: 0.918091\n", - "epoch: 17, avg loss: 0.660566, avg accuracy: 0.918100\n", - "epoch: 18, avg loss: 0.653175, avg accuracy: 0.918264\n", - "epoch: 19, avg loss: 0.638035, avg accuracy: 0.919855\n", - "epoch: 20, avg loss: 0.631894, avg accuracy: 0.919491\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " X, Y = shuffle(X, Y)\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k + batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_answer)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)\n", - " predicted, accuracy, loss, _ = sess.run([tf.argmax(model.logits,2),\n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y,\n", - " model.X_seq_len:seq_x,\n", - " model.Y_seq_len:seq_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: you can send weather balloons up into the stratosphere , collect microbes , see what 's up there .\n", - "REAL ANSWER: bạn có thể thả khí cầu thời tiết lên tầng tĩnh khí , thu thập vi khuẩn , xem điều gì đang xảy ra trên đó .\n", - "PREDICTED ANSWER: bạn có thể có tôi , , , " , , , , , , , , , , . . \n", - "\n", - "row 2\n", - "QUESTION: you can make a biocensor out of yeast to detect pollutants in water .\n", - "REAL ANSWER: bạn có thể làm ra một dụng cụ kiểm duyệt sinh học từ men để phát hiện chất gây ô nhiễm trong nước .\n", - "PREDICTED ANSWER: bạn có thể có một một một một , , của , , , . . \n", - "\n", - "row 3\n", - "QUESTION: she didn 't expect me to go there .\n", - "REAL ANSWER: chị ấy khồng nghĩ tôi sẽ đi .\n", - "PREDICTED ANSWER: chị đây : , tôi , tôi , . . \n", - "\n", - "row 4\n", - "QUESTION: its artists told stories across national boundaries , in as many languages , genres and philosophies as one can imagine .\n", - "REAL ANSWER: nó là những câu chuyện kể của các nghệ sĩ vượt qua các ranh giới quốc gia , dưới vô vàn ngôn ngữ , thể loại và triết lý mà một người có thể tưởng tượng ra được .\n", - "PREDICTED ANSWER: tôi là một , là , tôi , , , , , , , , , , , , tôi có . . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/7.basic-birnn-seq2seq.ipynb b/neural-machine-translation/7.basic-birnn-seq2seq.ipynb new file mode 100644 index 0000000..67ec235 --- /dev/null +++ b/neural-machine-translation/7.basic-birnn-seq2seq.ipynb @@ -0,0 +1,903 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '3'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(size_layer, reuse=False):\n", + " return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", + " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", + " print(encoder_embedded)\n", + " \n", + " for n in range(num_layers):\n", + " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", + " cell_fw = cells(size_layer // 2),\n", + " cell_bw = cells(size_layer // 2),\n", + " inputs = encoder_embedded,\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32,\n", + " scope = 'bidirectional_rnn_%d'%(n))\n", + " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", + "\n", + " bi_state = tf.concat((state_fw,state_bw), -1)\n", + " last_state = tuple([bi_state] * num_layers)\n", + " \n", + " with tf.variable_scope(\"decoder\"):\n", + " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = last_state,\n", + " dtype = tf.float32)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 13:59:30.940299 139930102572864 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 13:59:30.995121 139930102572864 deprecation.py:323] From :10: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 13:59:30.997009 139930102572864 deprecation.py:323] From :34: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n", + "W0902 13:59:30.998358 139930102572864 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 13:59:31.160508 139930102572864 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 13:59:31.172376 139930102572864 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:459: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tensor(\"embedding_lookup/Identity:0\", shape=(?, ?, 256), dtype=float32)\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "W0902 13:59:31.293437 139930102572864 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 13:59:31.701896 139930102572864 deprecation.py:323] From :41: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 13:59:32.055593 139930102572864 deprecation.py:323] From :46: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n", + "W0902 13:59:33.010119 139930102572864 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [05:52<00:00, 2.95it/s, accuracy=0.0673, cost=6.9] \n", + "minibatch loop: 100%|██████████| 23/23 [00:03<00:00, 6.93it/s, accuracy=0.0791, cost=6.69]\n", + "minibatch loop: 0%| | 0/1042 [00:00 phút . của của phụ nữ ba , giới thế thế về , về , kinh những , , trong trong của của của của . cô gái cô gái cô cô cô gái cô cô dì cô tôi và đêm , và , một trong trong ở Bờ Diego năm năm năm , , , năm đã sống đời khoảnh bé và bao bao . tôi - - - bé cô trai tôi ở đã San và và và và nay\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là một . chuyện . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Rất là một một hơi là là là bốt bốt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Để tôi tôi cho bạn về số về về . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy tưởng tượng đầu tiên : một đàn ông : ông của của của . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Anh là là cựu thơ , , , , , đàn , đàn đời đời đời trong trong , trong . . của . . của . và và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy tưởng anh khi khi đang ở Trung , , , , , , chúng của đã đã sự . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Từ , , , tôi , tôi bạn , , giờ giờ giờ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh ta lưỡi vào im . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Anh ấy chết lên mất bởi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Anh ấy là của tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi biết bao giờ ta ta ta sống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng cả cả sống chúng ta ta hơn hơn ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Mẹ tôi tôi bao giờ tôi quên quên mình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Trách mơ của tôi không không chấp quyết để phải . trong trong , và và , tôi tôi học tôi học , , , học tôi tôi chúng chúng chúng chúng chúng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Tác tiếp tiếp theo , , , không là một teen San trong , đầu đầu đầu từ ra , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi tôi Yvonne Ferren , , khi khi , - - - - - một trong một một một , , bé . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Với với , , , tôi tôi sốc tôi tôi một một : . . của của và và và và và và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Nó là tôi tôi tôi ấy ấy ấy cô không không . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau tháng đã thư , , Diego , , , sông ra ra một một Diego . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/8.lstm-birnn-seq2seq-manual.ipynb b/neural-machine-translation/8.lstm-birnn-seq2seq-manual.ipynb deleted file mode 100644 index f5a8b22..0000000 --- a/neural-machine-translation/8.lstm-birnn-seq2seq-manual.ipynb +++ /dev/null @@ -1,410 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(size,reuse=False):\n", - " return tf.nn.rnn_cell.LSTMCell(size,initializer=tf.orthogonal_initializer(),reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " \n", - " for n in range(num_layers):\n", - " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", - " cell_fw = cells(size_layer // 2),\n", - " cell_bw = cells(size_layer // 2),\n", - " inputs = encoder_embedded,\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32,\n", - " scope = 'bidirectional_rnn_%d'%(n))\n", - " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", - "\n", - " bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n", - " bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n", - " bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n", - " last_state = tuple([bi_lstm_state] * num_layers)\n", - " \n", - " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", - " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", - "\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 128\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "maxlen_question = max([len(x) for x in X]) * 2\n", - "maxlen_answer = max([len(y) for y in Y]) * 2\n", - "maxlen_question, maxlen_answer" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int, maxlen):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = maxlen\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(maxlen)\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 3.057538, avg accuracy: 0.882773\n", - "epoch: 2, avg loss: 0.838540, avg accuracy: 0.910864\n", - "epoch: 3, avg loss: 0.763301, avg accuracy: 0.911609\n", - "epoch: 4, avg loss: 0.735146, avg accuracy: 0.912718\n", - "epoch: 5, avg loss: 0.724207, avg accuracy: 0.913800\n", - "epoch: 6, avg loss: 0.722383, avg accuracy: 0.913736\n", - "epoch: 7, avg loss: 0.714579, avg accuracy: 0.913891\n", - "epoch: 8, avg loss: 0.698534, avg accuracy: 0.915482\n", - "epoch: 9, avg loss: 0.708854, avg accuracy: 0.913973\n", - "epoch: 10, avg loss: 0.707431, avg accuracy: 0.912118\n", - "epoch: 11, avg loss: 0.683583, avg accuracy: 0.915700\n", - "epoch: 12, avg loss: 0.672532, avg accuracy: 0.916382\n", - "epoch: 13, avg loss: 0.675660, avg accuracy: 0.916018\n", - "epoch: 14, avg loss: 0.659123, avg accuracy: 0.917927\n", - "epoch: 15, avg loss: 0.657314, avg accuracy: 0.917800\n", - "epoch: 16, avg loss: 0.649246, avg accuracy: 0.918791\n", - "epoch: 17, avg loss: 0.654536, avg accuracy: 0.918145\n", - "epoch: 18, avg loss: 0.647920, avg accuracy: 0.918618\n", - "epoch: 19, avg loss: 0.642469, avg accuracy: 0.919536\n", - "epoch: 20, avg loss: 0.648654, avg accuracy: 0.918473\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " X, Y = shuffle(X, Y)\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k + batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_answer)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)\n", - " predicted, accuracy, loss, _ = sess.run([tf.argmax(model.logits,2),\n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y,\n", - " model.X_seq_len:seq_x,\n", - " model.Y_seq_len:seq_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: a biohacker in germany , a journalist , wanted to know whose dog was leaving little presents on his street ?\n", - "REAL ANSWER: một nhà biohacker người đức , một nhà báo , muốn biết chó của ai đã để lại những " món quà " nho nhỏ trên đường ?\n", - "PREDICTED ANSWER: và tôi , , , , , , , , , , , , , , , , , , , , , , , . . \n", - "\n", - "row 2\n", - "QUESTION: so " rudolph the red-nosed reindeer " -- you know it ?\n", - "REAL ANSWER: bài " con tuần lộc mũi đỏ rudolph " -- bạn biết bài đó chứ ?\n", - "PREDICTED ANSWER: và tôi tôi , , , , , , , , , , , . . \n", - "\n", - "row 3\n", - "QUESTION: and it was with great delight that we found young people up and down the country explaining with authority what filibustering was and why the lords might defy their bedtime on a point of principle .\n", - "REAL ANSWER: và thật vui vô cùng khi chúng tôi thấy những bạn trẻ trên khắp đất nước giải thích với nhà cầm quyền rằng cản trở các đạo luật là gì và tại sao các nhà cầm quyền có thể định giờ ngủ của họ theo một nguyên tắc nào đó .\n", - "PREDICTED ANSWER: và và , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , \n", - "\n", - "row 4\n", - "QUESTION: she didn 't expect me to go there .\n", - "REAL ANSWER: chị ấy khồng nghĩ tôi sẽ đi .\n", - "PREDICTED ANSWER: tôi tôi tôi tôi tôi . . . . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/8.lstm-birnn-seq2seq.ipynb b/neural-machine-translation/8.lstm-birnn-seq2seq.ipynb new file mode 100644 index 0000000..ab5bd7d --- /dev/null +++ b/neural-machine-translation/8.lstm-birnn-seq2seq.ipynb @@ -0,0 +1,905 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '0'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(size_layer, reuse=False):\n", + " return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", + " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", + " print(encoder_embedded)\n", + " \n", + " for n in range(num_layers):\n", + " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", + " cell_fw = cells(size_layer // 2),\n", + " cell_bw = cells(size_layer // 2),\n", + " inputs = encoder_embedded,\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32,\n", + " scope = 'bidirectional_rnn_%d'%(n))\n", + " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", + "\n", + " bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n", + " bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n", + " bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n", + " last_state = tuple([bi_lstm_state] * num_layers)\n", + " \n", + " with tf.variable_scope(\"decoder\"):\n", + " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = last_state,\n", + " dtype = tf.float32)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 17:54:18.444416 139777031710528 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 17:54:18.491165 139777031710528 deprecation.py:323] From :10: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 17:54:18.493103 139777031710528 deprecation.py:323] From :34: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n", + "W0902 17:54:18.494376 139777031710528 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 17:54:18.680064 139777031710528 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tensor(\"embedding_lookup/Identity:0\", shape=(?, ?, 256), dtype=float32)\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "W0902 17:54:19.273821 139777031710528 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 17:54:19.796666 139777031710528 deprecation.py:323] From :43: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 17:54:20.194027 139777031710528 deprecation.py:323] From :48: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n", + "W0902 17:54:20.199417 139777031710528 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 17:54:21.235442 139777031710528 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [09:02<00:00, 1.92it/s, accuracy=0.106, cost=6.56] \n", + "minibatch loop: 100%|██████████| 23/23 [00:04<00:00, 4.94it/s, accuracy=0.0904, cost=6.4] \n", + "minibatch loop: 0%| | 0/1042 [00:00 , , , về đáng trọng cực cực đến thế ra những lực một một trỗi đã trong hôn hôn nữ nữ đã và và , , , chồng chồng chồng , và chị và , và tôi tôi mình mình ở ở ở trên nhanh màu Youtube , lần còn thấy , đã đã ra nhiều người nhiều nhiều trên và và và và bài chuyện nữ này này này và chúng chúng có ở\n", + "0 actual: Làm sao tôi có thể trình bày trong phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là một câu diễn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Đây là một cú kỳ cực ta đầu . lại . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Hãy tôi kể bạn bạn về số . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Thử tưởng tượng tượng tiên tiên đầu : : xà : cuộc cuộc sống sống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Ông là là nhà , nhà nhà nhà nhà , một một người người có cuộc cuộc cuộc bản bản bản của của của bản bản bảo bảo vệ bảo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Tưởng tượng rằng anh anh là sự truyền càng dần , , quan , , sự sự cuộc cuộc sống đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: vời cho ông anh thời các anh anh ông bạn ấy anh anh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh bơi bơi lội lại lại . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Anh đã đã qua qua lịch lịch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Cậu ấy là ông tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi chưa bao giờ đời anh sống sống sống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng cuộc sống chúng ta còn hơn hơn hơn hơn ức . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Cha tôi không bao giờ giờ tôi quên giờ đời . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Tôi tôi tôi không không là vệ của tôi tôi tôi ở , tôi tôi được , , là học học tôi tôi học dạy , , để , , chúng chúng tôi tôi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Một kế theo theo là đầu đầu đầu tâm tâm tâm đáy đáy đầu đáy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi là một một một , mẹ trong một một một một gia gia gia với với nhỏ nhỏ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Với với sống cuộc sống cuộc cuộc đã có mang mang mang cuộc : sự sự sống đình đình đình sống sống sống sống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Đó là cô gọi cô rằng rằng ấy không công công công . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Sau sau sau sau sau sau khi đồng nhắc về , , , , , trên trên , nước , , đất đất nước . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/9.gru-birnn-seq2seq-manual.ipynb b/neural-machine-translation/9.gru-birnn-seq2seq-manual.ipynb deleted file mode 100644 index 0bda4d1..0000000 --- a/neural-machine-translation/9.gru-birnn-seq2seq-manual.ipynb +++ /dev/null @@ -1,401 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import tensorflow as tf\n", - "from sklearn.utils import shuffle\n", - "import re\n", - "import time\n", - "import collections\n", - "import os" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "def build_dataset(words, n_words, atleast=1):\n", - " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", - " counter = collections.Counter(words).most_common(n_words)\n", - " counter = [i for i in counter if i[1] >= atleast]\n", - " count.extend(counter)\n", - " dictionary = dict()\n", - " for word, _ in count:\n", - " dictionary[word] = len(dictionary)\n", - " data = list()\n", - " unk_count = 0\n", - " for word in words:\n", - " index = dictionary.get(word, 0)\n", - " if index == 0:\n", - " unk_count += 1\n", - " data.append(index)\n", - " count[0][1] = unk_count\n", - " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", - " return data, count, dictionary, reversed_dictionary" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "len from: 500, len to: 500\n" - ] - } - ], - "source": [ - "with open('english-train', 'r') as fopen:\n", - " text_from = fopen.read().lower().split('\\n')[:-1]\n", - "with open('vietnam-train', 'r') as fopen:\n", - " text_to = fopen.read().lower().split('\\n')[:-1]\n", - "print('len from: %d, len to: %d'%(len(text_from), len(text_to)))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab from size: 1935\n", - "Most common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\n", - "Sample data [482, 483, 78, 6, 137, 484, 10, 226, 787, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n" - ] - } - ], - "source": [ - "concat_from = ' '.join(text_from).split()\n", - "vocabulary_size_from = len(list(set(concat_from)))\n", - "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", - "print('vocab from size: %d'%(vocabulary_size_from))\n", - "print('Most common words', count_from[4:10])\n", - "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "vocab to size: 1461\n", - "Most common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\n", - "Sample data [84, 22, 668, 73, 10, 389, 110, 34, 81, 299] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" - ] - } - ], - "source": [ - "concat_to = ' '.join(text_to).split()\n", - "vocabulary_size_to = len(list(set(concat_to)))\n", - "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", - "print('vocab to size: %d'%(vocabulary_size_to))\n", - "print('Most common words', count_to[4:10])\n", - "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [], - "source": [ - "GO = dictionary_from['GO']\n", - "PAD = dictionary_from['PAD']\n", - "EOS = dictionary_from['EOS']\n", - "UNK = dictionary_from['UNK']" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(len(text_to)):\n", - " text_to[i] += ' EOS'" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "class Chatbot:\n", - " def __init__(self, size_layer, num_layers, embedded_size,\n", - " from_dict_size, to_dict_size, learning_rate, batch_size):\n", - " \n", - " def cells(size,reuse=False):\n", - " return tf.nn.rnn_cell.GRUCell(size,reuse=reuse)\n", - " \n", - " self.X = tf.placeholder(tf.int32, [None, None])\n", - " self.Y = tf.placeholder(tf.int32, [None, None])\n", - " self.X_seq_len = tf.placeholder(tf.int32, [None])\n", - " self.Y_seq_len = tf.placeholder(tf.int32, [None])\n", - " batch_size = tf.shape(self.X)[0]\n", - " \n", - " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", - " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", - " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", - " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", - " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", - " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", - " \n", - " for n in range(num_layers):\n", - " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", - " cell_fw = cells(size_layer // 2),\n", - " cell_bw = cells(size_layer // 2),\n", - " inputs = encoder_embedded,\n", - " sequence_length = self.X_seq_len,\n", - " dtype = tf.float32,\n", - " scope = 'bidirectional_rnn_%d'%(n))\n", - " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", - "\n", - " bi_state = tf.concat((state_fw,state_bw), -1)\n", - " last_state = tuple([bi_state] * num_layers)\n", - " \n", - " with tf.variable_scope(\"decoder\"):\n", - " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n", - " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", - " initial_state = last_state,\n", - " dtype = tf.float32)\n", - " self.logits = tf.layers.dense(outputs,to_dict_size)\n", - "\n", - " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", - " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n", - " targets = self.Y,\n", - " weights = masks)\n", - " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", - " y_t = tf.argmax(self.logits,axis=2)\n", - " y_t = tf.cast(y_t, tf.int32)\n", - " self.prediction = tf.boolean_mask(y_t, masks)\n", - " mask_label = tf.boolean_mask(self.Y, masks)\n", - " correct_pred = tf.equal(self.prediction, mask_label)\n", - " correct_index = tf.cast(correct_pred, tf.float32)\n", - " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "size_layer = 256\n", - "num_layers = 2\n", - "embedded_size = 128\n", - "learning_rate = 0.001\n", - "batch_size = 16\n", - "epoch = 20" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "tf.reset_default_graph()\n", - "sess = tf.InteractiveSession()\n", - "model = Chatbot(size_layer, num_layers, embedded_size, len(dictionary_from), \n", - " len(dictionary_to), learning_rate,batch_size)\n", - "sess.run(tf.global_variables_initializer())" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "def str_idx(corpus, dic):\n", - " X = []\n", - " for i in corpus:\n", - " ints = []\n", - " for k in i.split():\n", - " ints.append(dic.get(k,UNK))\n", - " X.append(ints)\n", - " return X" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "X = str_idx(text_from, dictionary_from)\n", - "Y = str_idx(text_to, dictionary_to)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(174, 220)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "maxlen_question = max([len(x) for x in X]) * 2\n", - "maxlen_answer = max([len(y) for y in Y]) * 2\n", - "maxlen_question, maxlen_answer" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "def pad_sentence_batch(sentence_batch, pad_int, maxlen):\n", - " padded_seqs = []\n", - " seq_lens = []\n", - " max_sentence_len = maxlen\n", - " for sentence in sentence_batch:\n", - " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", - " seq_lens.append(maxlen)\n", - " return padded_seqs, seq_lens" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "epoch: 1, avg loss: 1.600767, avg accuracy: 0.882627\n", - "epoch: 2, avg loss: 0.739814, avg accuracy: 0.913555\n", - "epoch: 3, avg loss: 0.725232, avg accuracy: 0.913864\n", - "epoch: 4, avg loss: 0.716623, avg accuracy: 0.913936\n", - "epoch: 5, avg loss: 0.709351, avg accuracy: 0.914400\n", - "epoch: 6, avg loss: 0.689928, avg accuracy: 0.916364\n", - "epoch: 7, avg loss: 0.680712, avg accuracy: 0.916782\n", - "epoch: 8, avg loss: 0.670387, avg accuracy: 0.916964\n", - "epoch: 9, avg loss: 0.671381, avg accuracy: 0.916055\n", - "epoch: 10, avg loss: 0.668878, avg accuracy: 0.915600\n", - "epoch: 11, avg loss: 0.649184, avg accuracy: 0.917282\n", - "epoch: 12, avg loss: 0.638758, avg accuracy: 0.917464\n", - "epoch: 13, avg loss: 0.614561, avg accuracy: 0.920173\n", - "epoch: 14, avg loss: 0.607420, avg accuracy: 0.919564\n", - "epoch: 15, avg loss: 0.604646, avg accuracy: 0.918409\n", - "epoch: 16, avg loss: 0.594362, avg accuracy: 0.918727\n", - "epoch: 17, avg loss: 0.564419, avg accuracy: 0.922173\n", - "epoch: 18, avg loss: 0.557343, avg accuracy: 0.921609\n", - "epoch: 19, avg loss: 0.551805, avg accuracy: 0.921545\n", - "epoch: 20, avg loss: 0.538976, avg accuracy: 0.922818\n" - ] - } - ], - "source": [ - "for i in range(epoch):\n", - " total_loss, total_accuracy = 0, 0\n", - " X, Y = shuffle(X, Y)\n", - " for k in range(0, len(text_to), batch_size):\n", - " index = min(k + batch_size, len(text_to))\n", - " batch_x, seq_x = pad_sentence_batch(X[k: index], PAD, maxlen_answer)\n", - " batch_y, seq_y = pad_sentence_batch(Y[k: index], PAD, maxlen_answer)\n", - " predicted, accuracy, loss, _ = sess.run([tf.argmax(model.logits,2),\n", - " model.accuracy, model.cost, model.optimizer], \n", - " feed_dict={model.X:batch_x,\n", - " model.Y:batch_y,\n", - " model.X_seq_len:seq_x,\n", - " model.Y_seq_len:seq_y})\n", - " total_loss += loss\n", - " total_accuracy += accuracy\n", - " total_loss /= (len(text_to) / batch_size)\n", - " total_accuracy /= (len(text_to) / batch_size)\n", - " print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "row 1\n", - "QUESTION: this is such a new area , and as we say back in brooklyn , you ain 't seen nothin ' yet .\n", - "REAL ANSWER: đây là một lĩnh vực rất mới , và như chúng tôi nói ở brooklyn , bạn còn chưa thấy gì cả đâu . .\n", - "PREDICTED ANSWER: đây là là là là , , , , , , , , , , , , , , , . . . . \n", - "\n", - "row 2\n", - "QUESTION: so put your arms back up and flex your bicep .\n", - "REAL ANSWER: vâng , hãy giơ tay lên và cong cơ cánh tay lại .\n", - "PREDICTED ANSWER: đây đây là là là , , , , , , . . \n", - "\n", - "row 3\n", - "QUESTION: we stopped looking at him as a problem , and we started to look at him as an opportunity to improve .\n", - "REAL ANSWER: chúng tôi không còn coi bé là một vấn đề nữa , và chúng tôi bắt đầu coi bé như một cơ hội để trở nên tốt hơn .\n", - "PREDICTED ANSWER: chúng chúng tôi chúng chúng chúng chúng chúng chúng chúng chúng chúng chúng chúng chúng và và và và chúng chúng chúng chúng tôi . . . \n", - "\n", - "row 4\n", - "QUESTION: we reverse engineer lab equipment .\n", - "REAL ANSWER: chúng tôi tự chế dụng cụ phòng thí nghiệm .\n", - "PREDICTED ANSWER: chúng tôi tôi chúng bay để để . . . \n", - "\n" - ] - } - ], - "source": [ - "for i in range(len(batch_x)):\n", - " print('row %d'%(i+1))\n", - " print('QUESTION:',' '.join([rev_dictionary_from[n] for n in batch_x[i] if n not in [0,1,2,3]]))\n", - " print('REAL ANSWER:',' '.join([rev_dictionary_to[n] for n in batch_y[i] if n not in[0,1,2,3]]))\n", - " print('PREDICTED ANSWER:',' '.join([rev_dictionary_to[n] for n in predicted[i] if n not in[0,1,2,3]]),'\\n')" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.8" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/neural-machine-translation/9.gru-birnn-seq2seq.ipynb b/neural-machine-translation/9.gru-birnn-seq2seq.ipynb new file mode 100644 index 0000000..1802bd5 --- /dev/null +++ b/neural-machine-translation/9.gru-birnn-seq2seq.ipynb @@ -0,0 +1,906 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.environ['CUDA_VISIBLE_DEVICES'] = '1'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import tensorflow as tf" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "with open('train-test.json') as fopen:\n", + " dataset = json.load(fopen)\n", + " \n", + "with open('dictionary.json') as fopen:\n", + " dictionary = json.load(fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = dataset['train_X']\n", + "train_Y = dataset['train_Y']\n", + "test_X = dataset['test_X']\n", + "test_Y = dataset['test_Y']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['from', 'to'])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "dictionary_from = dictionary['from']['dictionary']\n", + "rev_dictionary_from = dictionary['from']['rev_dictionary']\n", + "\n", + "dictionary_to = dictionary['to']['dictionary']\n", + "rev_dictionary_to = dictionary['to']['rev_dictionary']" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "GO = dictionary_from['GO']\n", + "PAD = dictionary_from['PAD']\n", + "EOS = dictionary_from['EOS']\n", + "UNK = dictionary_from['UNK']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Rachel Pike : The science behind a climate headline EOS'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(train_X)):\n", + " train_X[i] += ' EOS'\n", + " \n", + "train_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'How can I speak in minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "for i in range(len(test_X)):\n", + " test_X[i] += ' EOS'\n", + " \n", + "test_X[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def pad_second_dim(x, desired_size):\n", + " padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n", + " return tf.concat([x, padding], 1)\n", + "\n", + "class Translator:\n", + " def __init__(self, size_layer, num_layers, embedded_size,\n", + " from_dict_size, to_dict_size, learning_rate, batch_size):\n", + " \n", + " def cells(size_layer, reuse=False):\n", + " return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n", + " \n", + " self.X = tf.placeholder(tf.int32, [None, None])\n", + " self.Y = tf.placeholder(tf.int32, [None, None])\n", + " \n", + " self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n", + " self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n", + " batch_size = tf.shape(self.X)[0]\n", + " \n", + " encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n", + " decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n", + " encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n", + " main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n", + " decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n", + " decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n", + " print(encoder_embedded)\n", + " \n", + " for n in range(num_layers):\n", + " (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n", + " cell_fw = cells(size_layer // 2),\n", + " cell_bw = cells(size_layer // 2),\n", + " inputs = encoder_embedded,\n", + " sequence_length = self.X_seq_len,\n", + " dtype = tf.float32,\n", + " scope = 'bidirectional_rnn_%d'%(n))\n", + " encoder_embedded = tf.concat((out_fw, out_bw), 2)\n", + "\n", + " bi_state = tf.concat((state_fw,state_bw), -1)\n", + " last_state = tuple([bi_state] * num_layers)\n", + " \n", + " with tf.variable_scope(\"decoder\"):\n", + " rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n", + " outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n", + " sequence_length=self.X_seq_len,\n", + " initial_state = last_state,\n", + " dtype = tf.float32)\n", + " self.logits = tf.layers.dense(outputs,to_dict_size)\n", + " \n", + " self.training_logits = self.logits[:, :tf.reduce_max(self.Y_seq_len)]\n", + " self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n", + " \n", + " masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n", + " self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n", + " targets = self.Y,\n", + " weights = masks)\n", + " self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n", + " y_t = tf.argmax(self.training_logits,axis=2)\n", + " y_t = tf.cast(y_t, tf.int32)\n", + " self.prediction = tf.boolean_mask(y_t, masks)\n", + " mask_label = tf.boolean_mask(self.Y, masks)\n", + " correct_pred = tf.equal(self.prediction, mask_label)\n", + " correct_index = tf.cast(correct_pred, tf.float32)\n", + " self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "size_layer = 512\n", + "num_layers = 2\n", + "embedded_size = 256\n", + "learning_rate = 1e-3\n", + "batch_size = 128\n", + "epoch = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: Logging before flag parsing goes to stderr.\n", + "W0902 17:52:58.847471 140499052144448 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "reduction_indices is deprecated, use axis instead\n", + "W0902 17:52:58.896279 140499052144448 deprecation.py:323] From :10: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 17:52:58.897986 140499052144448 deprecation.py:323] From :34: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n", + "W0902 17:52:58.899206 140499052144448 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n", + "W0902 17:52:59.051297 140499052144448 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 17:52:59.062811 140499052144448 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:564: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n", + "W0902 17:52:59.079363 140499052144448 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:574: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Call initializer instance with the dtype argument instead of passing it to the constructor\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Tensor(\"embedding_lookup/Identity:0\", shape=(?, ?, 256), dtype=float32)\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "W0902 17:52:59.296139 140499052144448 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support..wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", + "W0902 17:52:59.726474 140499052144448 deprecation.py:323] From :41: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n", + "W0902 17:53:00.197296 140499052144448 deprecation.py:323] From :46: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", + "Instructions for updating:\n", + "Use keras.layers.dense instead.\n", + "W0902 17:53:01.187949 140499052144448 lazy_loader.py:50] \n", + "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n", + "For more information, please see:\n", + " * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n", + " * https://github.com/tensorflow/addons\n", + " * https://github.com/tensorflow/io (for I/O related ops)\n", + "If you depend on functionality not listed there, please file an issue.\n", + "\n" + ] + } + ], + "source": [ + "tf.reset_default_graph()\n", + "sess = tf.InteractiveSession()\n", + "model = Translator(size_layer, num_layers, embedded_size, len(dictionary_from), \n", + " len(dictionary_to), learning_rate,batch_size)\n", + "sess.run(tf.global_variables_initializer())" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def str_idx(corpus, dic):\n", + " X = []\n", + " for i in corpus:\n", + " ints = []\n", + " for k in i.split():\n", + " ints.append(dic.get(k,UNK))\n", + " X.append(ints)\n", + " return X\n", + "\n", + "def pad_sentence_batch(sentence_batch, pad_int):\n", + " padded_seqs = []\n", + " seq_lens = []\n", + " max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n", + " for sentence in sentence_batch:\n", + " padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n", + " seq_lens.append(len(sentence))\n", + " return padded_seqs, seq_lens" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "train_X = str_idx(train_X, dictionary_from)\n", + "test_X = str_idx(test_X, dictionary_from)\n", + "train_Y = str_idx(train_Y, dictionary_to)\n", + "test_Y = str_idx(test_Y, dictionary_to)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "minibatch loop: 100%|██████████| 1042/1042 [08:43<00:00, 1.99it/s, accuracy=0.11, cost=6.57] \n", + "minibatch loop: 100%|██████████| 23/23 [00:04<00:00, 5.54it/s, accuracy=0.113, cost=6.38] \n", + "minibatch loop: 0%| | 0/1042 [00:00 phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n", + "\n", + "1 predict: Đây không phải là là thành thành thành . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "1 actual: Câu chuyện này chưa kết thúc .\n", + "\n", + "2 predict: Đây là là bài sắp phản xếp sắp chiều lại kết . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n", + "\n", + "3 predict: Tôi tôi nói các các một số số số những . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n", + "\n", + "4 predict: Hãy tưởng xem bản tiên tiên tiên đàn ông có một một thời cuộc cuộc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n", + "\n", + "5 predict: Ông là một một nhà , , nhà tập , một ông ông về một cả kho kho sự tin vọng vọng của nước nước nước lục trên trên và . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n", + "\n", + "6 predict: Hãy tưởng ông anh kiến về một về , , , nạn nạn là cuộc cuộc cuộc cuộc cuộc vẹn vẹn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n", + "\n", + "7 predict: Từ , , anh anh anh anh đã anh giờ giờ giờ anh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n", + "\n", + "8 predict: Anh ta lặng lặng im im . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "8 actual: Ông rút lui vào yên lặng .\n", + "\n", + "9 predict: Ông đã ngay đã lịch lịch lịch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "9 actual: Ông qua đời , bị lịch sử quật ngã .\n", + "\n", + "10 predict: Ông ta ông ông . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "10 actual: Ông là ông của tôi .\n", + "\n", + "11 predict: Tôi chưa bao biết biết biết biết trong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n", + "\n", + "12 predict: Nhưng sống sống của của chúng còn nhiều nhiều ức ức . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n", + "\n", + "13 predict: Cô tôi chưa bao bao tôi quên anh mình . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n", + "\n", + "14 predict: Mục đích của của là là dành nó nó nó là là dụng dụng dụng , tôi tôi là học học học học , sử cố nghiệm , . , , chúng chúng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n", + "\n", + "15 predict: Phía bên một tàu là một tàu tàu một một một một tàu đầu đầu một tinh sóng biển biển . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n", + "\n", + "16 predict: Mẹ tôi , tôi tôi tôi đời , tuổi hôn , gái tôi tôi năm , hôn hôn hôn hôn hôn hôn tôi bé bé . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "16 actual: Mẹ tôi , Mai , mới tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n", + "\n", + "17 predict: Với một ấy bà cuộc cuộc rời cuộc cuộc một trong cuộc cuộc : : cuộc cuộc khỏi đình đình và cuộc sống sống . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n", + "\n", + "18 predict: Cá của của bà bà của không không thành công công . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n", + "\n", + "19 predict: Vì vậy sau công tích đợt đợt đợt chú lý , , , cánh cánh bến bến vùi tràn biển một là . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", + "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n", + "\n" + ] + } + ], + "source": [ + "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n", + "\n", + "for i in range(test_size):\n", + " predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n", + " actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n", + " print(i, 'predict:', ' '.join(predict))\n", + " print(i, 'actual:', ' '.join(actual))\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/README.md b/neural-machine-translation/README.md index 7d252df..84429a9 100644 --- a/neural-machine-translation/README.md +++ b/neural-machine-translation/README.md @@ -1,28 +1,29 @@ ## How-to -1. Run any notebook using Jupyter Notebook. +1. Run [download-preprocess-dataset.ipynb](download-preprocess-dataset.ipynb) to download dataset and preprocessing. +2. Run any notebook using Jupyter Notebook. ## Accuracy, not sorted -Based on training accuracy for 20 epochs. +Trainset to train, validation and test set to test. Based on test accuracy for 20 epochs. **Accuracy based on word positions**. | name | accuracy | |------------------------------------------------------------|----------| -| 1.basic-seq2seq-manual | 0.915255 | -| 2.lstm-seq2seq-manual | 0.917009 | -| 3.gru-seq2seq-manual | 0.920200 | -| 4.basic-seq2seq-api-greedy | 0.960998 | -| 5.lstm-seq2seq-api-greedy | 0.202590 | -| 6.gru-seq2seq-greedy | 0.408099 | -| 7.basic-birnn-seq2seq-manual | 0.919491 | -| 8.lstm-birnn-seq2seq-manual | 0.918473 | -| 9.gru-birnn-seq2seq-manual | 0.922818 | -| 10.basic-birnn-seq2seq-greedy | 0.957355 | -| 11.lstm-birnn-seq2seq-greedy | 0.202628 | -| 12.gru-birnn-seq2seq-greedy | 0.484461 | -| 13.basic-seq2seq-luong | 0.916100 | -| 14.lstm-seq2seq-luong | 0.917736 | -| 15.gru-seq2seq-luong | 0.919482 | +| 1.basic-seq2seq-manual | 0.103391 | +| 2.lstm-seq2seq-manual | 0.118877 | +| 3.gru-seq2seq-manual | 0.115032 | +| 4.basic-seq2seq-api-greedy | 0.252812 | +| 5.lstm-seq2seq-api-greedy | 0.330939 | +| 6.gru-seq2seq-greedy | 0.312779 | +| 7.basic-birnn-seq2seq-manual | 0.125462 | +| 8.lstm-birnn-seq2seq-manual | 0.121065 | +| 9.gru-birnn-seq2seq-manual | 0.119774 | +| 10.basic-birnn-seq2seq-greedy | 0.274987 | +| 11.lstm-birnn-seq2seq-greedy | 0.342469 | +| 12.gru-birnn-seq2seq-greedy | 0.325840 | +| 13.basic-seq2seq-luong | 0.023959 | +| 14.lstm-seq2seq-luong | 0.130840 | +| 15.gru-seq2seq-luong | 0.073492 | | 16.basic-seq2seq-bahdanau | 0.915700 | | 17.lstm-seq2seq-bahdanau | 0.721833 | | 18.gru-seq2seq-bahdanau | 0.919218 | diff --git a/neural-machine-translation/download-preprocess-dataset.ipynb b/neural-machine-translation/download-preprocess-dataset.ipynb new file mode 100644 index 0000000..01c7e87 --- /dev/null +++ b/neural-machine-translation/download-preprocess-dataset.ipynb @@ -0,0 +1,429 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# !wget https://github.com/stefan-it/nmt-en-vi/raw/master/data/train-en-vi.tgz\n", + "# !tar -zxf train-en-vi.tgz\n", + "# !wget https://github.com/stefan-it/nmt-en-vi/raw/master/data/dev-2012-en-vi.tgz\n", + "# !tar -zxf dev-2012-en-vi.tgz\n", + "# !wget https://github.com/stefan-it/nmt-en-vi/raw/master/data/test-2013-en-vi.tgz\n", + "# !tar -zxf test-2013-en-vi.tgz" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# !pip3 install malaya --no-deps\n", + "# !pip3 install bert-tensorflow\n", + "# !pip3 install toolz\n", + "# !pip3 install pysastrawi\n", + "# !pip3 install fuzzywuzzy\n", + "# !pip3 install xgboost\n", + "# !pip3 install ftfy" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n", + "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" + ] + } + ], + "source": [ + "import malaya\n", + "import re\n", + "\n", + "tokenizer = malaya.preprocessing.SocialTokenizer().tokenize\n", + "\n", + "def is_number_regex(s):\n", + " if re.match(\"^\\d+?\\.\\d+?$\", s) is None:\n", + " return s.isdigit()\n", + " return True\n", + "\n", + "def preprocessing(string):\n", + " tokenized = tokenizer(string)\n", + " tokenized = ['' if is_number_regex(w) else w for w in tokenized]\n", + " return tokenized" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(133317, 133317)" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "with open('train.en') as fopen:\n", + " train_english = fopen.read().split('\\n')[:-1]\n", + " \n", + "with open('train.vi') as fopen:\n", + " train_vietnam = fopen.read().split('\\n')[:-1]\n", + " \n", + "len(train_english), len(train_vietnam)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "('Rachel Pike : The science behind a climate headline',\n", + " 'Khoa học đằng sau một tiêu đề về khí hậu')" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "train_english[0], train_vietnam[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "100%|██████████| 133317/133317 [00:16<00:00, 8024.56it/s]\n" + ] + } + ], + "source": [ + "from tqdm import tqdm\n", + "\n", + "for i in tqdm(range(len(train_english))):\n", + " train_english[i] = ' '.join(preprocessing(train_english[i]))" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "100%|██████████| 133317/133317 [00:21<00:00, 6136.78it/s]\n" + ] + } + ], + "source": [ + "for i in tqdm(range(len(train_vietnam))):\n", + " train_vietnam[i] = ' '.join(preprocessing(train_vietnam[i]))" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(1553, 1553)" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "with open('tst2012.en') as fopen:\n", + " test_english_2012 = fopen.read().split('\\n')[:-1]\n", + " \n", + "with open('tst2012.vi') as fopen:\n", + " test_vietnam_2012 = fopen.read().split('\\n')[:-1]\n", + " \n", + "len(test_english_2012), len(test_vietnam_2012)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "100%|██████████| 1553/1553 [00:00<00:00, 9039.32it/s]\n", + "100%|██████████| 1553/1553 [00:00<00:00, 6949.77it/s]\n" + ] + } + ], + "source": [ + "for i in tqdm(range(len(test_english_2012))):\n", + " test_english_2012[i] = ' '.join(preprocessing(test_english_2012[i]))\n", + " \n", + "for i in tqdm(range(len(test_vietnam_2012))):\n", + " test_vietnam_2012[i] = ' '.join(preprocessing(test_vietnam_2012[i]))" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(1268, 1268)" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "with open('tst2013.en') as fopen:\n", + " test_english_2013 = fopen.read().split('\\n')[:-1]\n", + " \n", + "with open('tst2013.vi') as fopen:\n", + " test_vietnam_2013 = fopen.read().split('\\n')[:-1]\n", + " \n", + "len(test_english_2013), len(test_vietnam_2013)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "100%|██████████| 1268/1268 [00:00<00:00, 2778.69it/s]\n", + "100%|██████████| 1268/1268 [00:00<00:00, 2050.06it/s]\n" + ] + } + ], + "source": [ + "for i in tqdm(range(len(test_english_2013))):\n", + " test_english_2013[i] = ' '.join(preprocessing(test_english_2013[i]))\n", + " \n", + "for i in tqdm(range(len(test_vietnam_2013))):\n", + " test_vietnam_2013[i] = ' '.join(preprocessing(test_vietnam_2013[i]))" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "train_X, train_Y = [], []\n", + "for i in range(len(train_english)):\n", + " if len(train_english[i].split()) > 250:\n", + " continue\n", + " train_X.append(train_english[i])\n", + " train_Y.append(train_vietnam[i])" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "test_X, test_Y = [], []\n", + "for i in range(len(test_english_2012)):\n", + " if len(test_english_2012[i].split()) > 250:\n", + " continue\n", + " test_X.append(test_english_2012[i])\n", + " test_Y.append(test_vietnam_2012[i])\n", + " \n", + "for i in range(len(test_english_2013)):\n", + " if len(test_english_2013[i].split()) > 250:\n", + " continue\n", + " test_X.append(test_english_2013[i])\n", + " test_Y.append(test_vietnam_2013[i])" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "import collections\n", + "import json\n", + "\n", + "def build_dataset(words, n_words, atleast=1):\n", + " count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n", + " counter = collections.Counter(words).most_common(n_words)\n", + " counter = [i for i in counter if i[1] >= atleast]\n", + " count.extend(counter)\n", + " dictionary = dict()\n", + " for word, _ in count:\n", + " dictionary[word] = len(dictionary)\n", + " data = list()\n", + " unk_count = 0\n", + " for word in words:\n", + " index = dictionary.get(word, 0)\n", + " if index == 0:\n", + " unk_count += 1\n", + " data.append(index)\n", + " count[0][1] = unk_count\n", + " reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n", + " return data, count, dictionary, reversed_dictionary" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "vocab from size: 47925\n", + "Most common words [(',', 155595), ('.', 134615), ('the', 102861), ('to', 65617), (\"'\", 63980), ('of', 60178)]\n", + "Sample data [6514, 16802, 55, 58, 335, 591, 11, 731, 5458, 132] ['Rachel', 'Pike', ':', 'The', 'science', 'behind', 'a', 'climate', 'headline', 'In']\n" + ] + } + ], + "source": [ + "concat_from = ' '.join(train_X).split()\n", + "vocabulary_size_from = len(list(set(concat_from)))\n", + "data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\n", + "print('vocab from size: %d'%(vocabulary_size_from))\n", + "print('Most common words', count_from[4:10])\n", + "print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "vocab to size: 22341\n", + "Most common words [(',', 128187), ('.', 125091), ('là', 57919), ('tôi', 51677), ('một', 48925), ('có', 48134)]\n", + "Sample data [1909, 66, 1135, 128, 8, 371, 111, 38, 411, 723] ['Khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n" + ] + } + ], + "source": [ + "concat_to = ' '.join(train_Y).split()\n", + "vocabulary_size_to = len(list(set(concat_to)))\n", + "data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\n", + "print('vocab to size: %d'%(vocabulary_size_to))\n", + "print('Most common words', count_to[4:10])\n", + "print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [], + "source": [ + "with open('train-test.json', 'w') as fopen:\n", + " json.dump({'train_X': train_X, 'train_Y': train_Y,\n", + " 'test_X': test_X,\n", + " 'test_Y': test_Y}, fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [], + "source": [ + "with open('dictionary.json', 'w') as fopen:\n", + " json.dump({'from': {'dictionary': dictionary_from, 'rev_dictionary': rev_dictionary_from},\n", + " 'to': {'dictionary': dictionary_to, 'rev_dictionary': rev_dictionary_to}}, fopen)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/neural-machine-translation/english-train b/neural-machine-translation/english-train deleted file mode 100644 index b6752f8..0000000 --- a/neural-machine-translation/english-train +++ /dev/null @@ -1,500 +0,0 @@ -Rachel Pike : The science behind a climate headline -In 4 minutes , atmospheric chemist Rachel Pike provides a glimpse of the massive scientific effort behind the bold headlines on climate change , with her team -- one of thousands who contributed -- taking a risky flight over the rainforest in pursuit of data on a key molecule . -I 'd like to talk to you today about the scale of the scientific effort that goes into making the headlines you see in the paper . -Headlines that look like this when they have to do with climate change , and headlines that look like this when they have to do with air quality or smog . -They are both two branches of the same field of atmospheric science . -Recently the headlines looked like this when the Intergovernmental Panel on Climate Change , or IPCC , put out their report on the state of understanding of the atmospheric system . -That report was written by 620 scientists from 40 countries . -They wrote almost a thousand pages on the topic . -And all of those pages were reviewed by another 400-plus scientists and reviewers , from 113 countries . -It 's a big community . It 's such a big community , in fact , that our annual gathering is the largest scientific meeting in the world . -Over 15,000 scientists go to San Francisco every year for that . -And every one of those scientists is in a research group , and every research group studies a wide variety of topics . -For us at Cambridge , it 's as varied as the El Niño oscillation , which affects weather and climate , to the assimilation of satellite data , to emissions from crops that produce biofuels , which is what I happen to study . -And in each one of these research areas , of which there are even more , there are PhD students , like me , and we study incredibly narrow topics , things as narrow as a few processes or a few molecules . -And one of the molecules I study is called isoprene , which is here . It 's a small organic molecule . You 've probably never heard of it . -The weight of a paper clip is approximately equal to 900 zeta-illion -- 10 to the 21st -- molecules of isoprene . -But despite its very small weight , enough of it is emitted into the atmosphere every year to equal the weight of all the people on the planet . -It 's a huge amount of stuff . It 's equal to the weight of methane . -And because it 's so much stuff , it 's really important for the atmospheric system . -Because it 's important to the atmospheric system , we go to all lengths to study this thing . -We blow it up and look at the pieces . -This is the EUPHORE Smog Chamber in Spain . -Atmospheric explosions , or full combustion , takes about 15,000 times longer than what happens in your car . -But still , we look at the pieces . -We run enormous models on supercomputers ; this is what I happen to do . -Our models have hundreds of thousands of grid boxes calculating hundreds of variables each , on minute timescales . -And it takes weeks to perform our integrations . -And we perform dozens of integrations in order to understand what 's happening . -We also fly all over the world looking for this thing . -I recently joined a field campaign in Malaysia . There are others . -We found a global atmospheric watchtower there , in the middle of the rainforest , and hung hundreds of thousands of dollars worth of scientific equipment off this tower , to look for isoprene , and of course , other things while we were there . -This is the tower in the middle of the rainforest , from above . -And this is the tower from below . -And on part of that field campaign we even brought an aircraft with us . -And this plane , the model , BA146 , which was run by FAAM , normally flies 120 to 130 people . -So maybe you took a similar aircraft to get here today . -But we didn 't just fly it . We were flying at 100 meters above the top of the canopy to measure this molecule -- incredibly dangerous stuff . -We have to fly at a special incline in order to make the measurements . -We hire military and test pilots to do the maneuvering . -We have to get special flight clearance . -And as you come around the banks in these valleys , the forces can get up to two Gs . -And the scientists have to be completely harnessed in in order to make measurements while they 're on board . -So , as you can imagine , the inside of this aircraft doesn 't look like any plane you would take on vacation . -It 's a flying laboratory that we took to make measurements in the region of this molecule . -We do all of this to understand the chemistry of one molecule . -And when one student like me has some sort of inclination or understanding about that molecule , they write one scientific paper on the subject . -And out of that field campaign we 'll probably get a few dozen papers on a few dozen processes or molecules . -And as a body of knowledge builds up , it will form one subsection , or one sub-subsection of an assessment like the IPCC , although we have others . -And each one of the 11 chapters of the IPCC has six to ten subsections . -So you can imagine the scale of the effort . -In each one of those assessments that we write , we always tag on a summary , and the summary is written for a non-scientific audience . -And we hand that summary to journalists and policy makers , in order to make headlines like these . -Thank you very much . -Christopher deCharms : A look inside the brain in real time -Neuroscientist and inventor Christopher deCharms demonstrates a new way to use fMRI to show brain activity -- thoughts , emotions , pain -- while it is happening . In other words , you can actually see how you feel . -Hi . I 'm going to ask you to raise your arms and wave back , just the way I am -- kind of a royal wave . -You can mimic what you can see . -You can program the hundreds of muscles in your arm . -Soon , you 'll be able to look inside your brain and program , control the hundreds of brain areas that you see there . -I 'm going to tell you about that technology . -People have wanted to look inside the human mind , the human brain , for thousands of years . -Well , coming out of the research labs just now , for our generation , is the possibility to do that . -People envision this as being very difficult . -You had to take a spaceship , shrink it down , inject it into the bloodstream . -It was terribly dangerous . -You could be attacked by white blood cells in the arteries . -But now , we have a real technology to do this . -We 're going to fly into my colleague Peter 's brain . -We 're going to do it non-invasively using MRI . -We don 't have to inject anything . We don 't need radiation . -We will be able to fly into the anatomy of Peter 's brain -- literally , fly into his body -- but more importantly , we can look into his mind . -When Peter moves his arm , that yellow spot you see there is the interface to the functioning of Peter 's mind taking place . -Now you 've seen before that with electrodes you can control robotic arms , that brain imaging and scanners can show you the insides of brains . -What 's new is that that process has typically taken days or months of analysis . -We 've collapsed that through technology to milliseconds , and that allows us to let Peter to look at his brain in real time as he 's inside the scanner . -He can look at these 65,000 points of activation per second . -If he can see this pattern in his own brain , he can learn how to control it . -There have been three ways to try to impact the brain : the therapist 's couch , pills and the knife . -This is a fourth alternative that you are soon going to have . -We all know that as we form thoughts , they form deep channels in our minds and in our brains . -Chronic pain is an example . If you burn yourself , you pull your hand away . -But if you 're still in pain in six months ' or six years ' time , it 's because these circuits are producing pain that 's no longer helping you . -If we can look at the activation in the brain that 's producing the pain , we can form 3D models and watch in real time the brain process information , and then we can select the areas that produce the pain . -So put your arms back up and flex your bicep . -Now imagine that you will soon be able to look inside your brain and select brain areas to do that same thing . -What you 're seeing here is , we 've selected the pathways in the brain of a chronic pain patient . -This may shock you , but we 're literally reading this person 's brain in real time . -They 're watching their own brain activation , and they 're controlling the pathway that produces their pain . -They 're learning to flex this system that releases their own endogenous opiates . -As they do it , in the upper left is a display that 's yoked to their brain activation of their own pain being controlled . -When they control their brain , they can control their pain . -This is an investigational technology , but , in clinical trials , we 're seeing a 44 to 64 percent decrease in chronic pain patients . -This is not " The Matrix . " You can only do this to yourself . You take control . -I 've seen inside my brain . You will too , soon . -When you do , what do you want to control ? -You will be able to look at all the aspects that make you yourself , all your experiences . -These are some of the areas we 're working on today that I don 't have time to go into in detail . -But I want to leave with you the big question . -We are the first generation that 's going to be able to enter into , using this technology , the human mind and brain . -Where will we take it ? -Beeban Kidron : The shared wonder of film -Movies have the power to create a shared narrative experience and to shape memories and worldviews . British film director Beeban Kidron invokes iconic film scenes -- from & lt ; em & gt ; Miracle in Milan & lt ; / em & gt ; to & lt ; em & gt ; Boyz n the Hood & lt ; / em & gt ; -- as she shows how her group FILMCLUB shares great films with kids . -Evidence suggests that humans in all ages and from all cultures create their identity in some kind of narrative form . -From mother to daughter , preacher to congregant , teacher to pupil , storyteller to audience . -Whether in cave paintings or the latest uses of the Internet , human beings have always told their histories and truths through parable and fable . -We are inveterate storytellers . -But where , in our increasingly secular and fragmented world , do we offer communality of experience , unmediated by our own furious consumerism ? -And what narrative , what history , what identity , what moral code are we imparting to our young ? -Cinema is arguably the 20th century 's most influential art form . -Its artists told stories across national boundaries , in as many languages , genres and philosophies as one can imagine . -Indeed , it is hard to find a subject that film has yet to tackle . -During the last decade we 've seen a vast integration of global media , now dominated by a culture of the Hollywood blockbuster . -We are increasingly offered a diet in which sensation , not story , is king . -What was common to us all 40 years ago -- the telling of stories between generations -- is now rarified . -As a filmmaker , it worried me . -As a human being , it puts the fear of God in me . -What future could the young build with so little grasp of where they 've come from and so few narratives of what 's possible ? -The irony is palpable ; technical access has never been greater , cultural access never weaker . -And so in 2006 we set up FILMCLUB , an organization that ran weekly film screenings in schools followed by discussions . -If we could raid the annals of 100 years of film , maybe we could build a narrative that would deliver meaning to the fragmented and restless world of the young . -Given the access to technology , even a school in a tiny rural hamlet could project a DVD onto a white board . -In the first nine months we ran 25 clubs across the U.K. , with kids in age groups between five and 18 watching a film uninterrupted for 90 minutes . -The films were curated and contextualized . -But the choice was theirs , and our audience quickly grew to choose the richest and most varied diet that we could provide . -The outcome , immediate . -It was an education of the most profound and transformative kind . -In groups as large as 150 and as small as three , these young people discovered new places , new thoughts , new perspectives . -By the time the pilot had finished , we had the names of a thousand schools that wished to join . -The film that changed my life is a 1951 film by Vittorio De Sica , " Miracle in Milan . " -It 's a remarkable comment on slums , poverty and aspiration . -I had seen the film on the occasion of my father 's 50th birthday . -Technology then meant we had to hire a viewing cinema , find and pay for the print and the projectionist . -But for my father , the emotional and artistic importance of De Sica 's vision was so great that he chose to celebrate his half-century with his three teenage children and 30 of their friends , " In order , " he said , " to pass the baton of concern and hope on to the next generation . " -In the last shot of " Miracle in Milan , " slum-dwellers float skyward on flying brooms . -Sixty years after the film was made and 30 years after I first saw it , I see young faces tilt up in awe , their incredulity matching mine . -And the speed with which they associate it with " Slumdog Millionaire " or the favelas in Rio speaks to the enduring nature . -In a FILMCLUB season about democracy and government , we screened " Mr. Smith Goes to Washington . " -Made in 1939 , the film is older than most of our members ' grandparents . -Frank Capra 's classic values independence and propriety . -It shows how to do right , how to be heroically awkward . -It is also an expression of faith in the political machine as a force of honor . -Shortly after " Mr. Smith " became a FILMCLUB classic , there was a week of all-night filibustering in the House of Lords . -And it was with great delight that we found young people up and down the country explaining with authority what filibustering was and why the Lords might defy their bedtime on a point of principle . -After all , Jimmy Stewart filibustered for two entire reels . -In choosing " Hotel Rwanda , " they explored genocide of the most brutal kind . -It provoked tears as well as incisive questions about unarmed peace-keeping forces and the double-dealing of a Western society that picks its moral fights with commodities in mind . -And when " Schindler 's List " demanded that they never forget , one child , full of the pain of consciousness , remarked , " We already forgot , otherwise how did ' Hotel Rwanda ' happen ? " -As they watch more films their lives got palpably richer . -" Pickpocket " started a debate about criminality disenfranchisement . -" To Sir , with Love " ignited its teen audience . -They celebrated a change in attitude towards non-white Britons , but railed against our restless school system that does not value collective identity , unlike that offered by Sidney Poitier 's careful tutelage . -By now , these thoughtful , opinionated , curious young people thought nothing of tackling films of all forms -- black and white , subtitled , documentary , non-narrative , fantasy -- and thought nothing of writing detailed reviews that competed to favor one film over another in passionate and increasingly sophisticated prose . -Six thousand reviews each school week vying for the honor of being review of the week . -From 25 clubs , we became hundreds , then thousands , until we were nearly a quarter of a million kids in 7,000 clubs right across the country . -And although the numbers were , and continue to be , extraordinary , what became more extraordinary was how the experience of critical and curious questioning translated into life . -Some of our kids started talking with their parents , others with their teachers , or with their friends . -And those without friends started making them . -The films provided communality across all manner of divide . -And the stories they held provided a shared experience . -" Persepolis " brought a daughter closer to her Iranian mother , and " Jaws " became the way in which one young boy was able to articulate the fear he 'd experienced in flight from violence that killed first his father then his mother , the latter thrown overboard on a boat journey . -Who was right , who wrong ? -What would they do under the same conditions ? -Was the tale told well ? -Was there a hidden message ? -How has the world changed ? How could it be different ? -A tsunami of questions flew out of the mouths of children who the world didn 't think were interested . -And they themselves had not known they cared . -And as they wrote and debated , rather than seeing the films as artifacts , they began to see themselves . -I have an aunt who is a wonderful storyteller . -In a moment she can invoke images of running barefoot on Table Mountain and playing cops and robbers . -Quite recently she told me that in 1948 , two of her sisters and my father traveled on a boat to Israel without my grandparents . -When the sailors mutinied at sea in a demand for humane conditions , it was these teenagers that fed the crew . -I was past 40 when my father died . -He never mentioned that journey . -My mother 's mother left Europe in a hurry without her husband , but with her three-year-old daughter and diamonds sewn into the hem of her skirt . -After two years in hiding , my grandfather appeared in London . -He was never right again . -And his story was hushed as he assimilated . -My story started in England with a clean slate and the silence of immigrant parents . -I had " Anne Frank , " " The Great Escape , " " Shoah , " " Triumph of the Will . " -It was Leni Riefenstahl in her elegant Nazi propaganda who gave context to what the family had to endure . -These films held what was too hurtful to say out loud , and they became more useful to me than the whispers of survivors and the occasional glimpse of a tattoo on a maiden aunt 's wrist . -Purists may feel that fiction dissipates the quest of real human understanding , that film is too crude to tell a complex and detailed history , or that filmmakers always serve drama over truth . -But within the reels lie purpose and meaning . -As one 12-year-old said after watching " Wizard of Oz , " " Every person should watch this , because unless you do you may not know that you too have a heart . " -We honor reading , why not honor watching with the same passion ? -Consider " Citizen Kane " as valuable as Jane Austen . -Agree that " Boyz n the Hood , " like Tennyson , offers an emotional landscape and a heightened understanding that work together . -Each a piece of memorable art , each a brick in the wall of who we are . -And it 's okay if we remember Tom Hanks better than astronaut Jim Lovell or have Ben Kingsley 's face superimposed onto that of Gandhi 's . -And though not real , Eve Harrington , Howard Beale , Mildred Pierce are an opportunity to discover what it is to be human , and no less helpful to understanding our life and times as Shakespeare is in illuminating the world of Elizabethan England . -We guessed that film , whose stories are a meeting place of drama , music , literature and human experience , would engage and inspire the young people participating in FILMCLUB . -What we could not have foreseen was the measurable improvements in behavior , confidence and academic achievement . -Once-reluctant students now race to school , talk to their teachers , fight , not on the playground , but to choose next week 's film -- young people who have found self-definition , ambition and an appetite for education and social engagement from the stories they have witnessed . -Our members defy the binary description of how we so often describe our young . -They are neither feral nor myopically self-absorbed . -They are , like other young people , negotiating a world with infinite choice , but little culture of how to find meaningful experience . -We appeared surprised at the behaviors of those who define themselves by the size of the tick on their shoes , yet acquisition has been the narrative we have offered . -If we want different values we have to tell a different story , a story that understands that an individual narrative is an essential component of a person 's identity , that a collective narrative is an essential component of a cultural identity , and without it it is impossible to imagine yourself as part of a group . -Because when these people get home after a screening of " Rear Window " and raise their gaze to the building next door , they have the tools to wonder who , apart from them , is out there and what is their story . -Thank you . -Ellen Jorgensen : Biohacking -- you can do it , too -We have personal computing , why not personal biotech ? That 's the question biologist Ellen Jorgensen and her colleagues asked themselves before opening Genspace , a nonprofit DIYbio lab in Brooklyn devoted to citizen science , where amateurs can go and tinker with biotechnology . Far from being a sinister Frankenstein 's lab , Genspace offers a long list of fun , creative and practical uses for DIYbio . -It 's a great time to be a molecular biologist . -Reading and writing DNA code is getting easier and cheaper . -By the end of this year , we 'll be able to sequence the three million bits of information in your genome in less than a day and for less than 1,000 euros . -Biotech is probably the most powerful and the fastest-growing technology sector . -It has the power , potentially , to replace our fossil fuels , to revolutionize medicine , and to touch every aspect of our daily lives . -So who gets to do it ? -I think we 'd all be pretty comfortable with this guy doing it . -But what about that guy ? -In 2009 , I first heard about DIYbio . -It 's a movement that -- it advocates making biotechnology accessible to everyone , not just scientists and people in government labs . -The idea is that if you open up the science and you allow diverse groups to participate , it could really stimulate innovation . -Putting technology in the hands of the end user is usually a good idea because they 've got the best idea of what their needs are . -And here 's this really sophisticated technology coming down the road , all these associated social , moral , ethical questions , and we scientists are just lousy at explaining to the public just exactly what it is we 're doing in those labs . -So wouldn 't it be nice if there was a place in your local neighborhood where you could go and learn about this stuff , do it hands-on ? -I thought so . -So , three years ago , I got together with some friends of mine who had similar aspirations and we founded Genspace . -It 's a nonprofit , a community biotech lab in Brooklyn , New York , and the idea was people could come , they could take classes and putter around in the lab in a very open , friendly atmosphere . -None of my previous experience prepared me for what came next . Can you guess ? -The press started calling us . -And the more we talked about how great it was to increase science literacy , the more they wanted to talk about us creating the next Frankenstein , and as a result , for the next six months , when you Googled my name , instead of getting my scientific papers , you got this . -[ " Am I a biohazard ? " ] It was pretty depressing . -The only thing that got us through that period was that we knew that all over the world , there were other people that were trying to do the same thing that we were . -They were opening biohacker spaces , and some of them were facing much greater challenges than we did , more regulations , less resources . -But now , three years later , here 's where we stand . -It 's a vibrant , global community of hackerspaces , and this is just the beginning . -These are some of the biggest ones , and there are others opening every day . -There 's one probably going to open up in Moscow , one in South Korea , and the cool thing is they each have their own individual flavor that grew out of the community they came out of . -Let me take you on a little tour . -Biohackers work alone . -We work in groups , in big cities — — and in small villages . -We reverse engineer lab equipment . -We genetically engineer bacteria . -We hack hardware , software , wetware , and , of course , the code of life . -We like to build things . -Then we like to take things apart . -We make things grow . -We make things glow . -And we make cells dance . -The spirit of these labs , it 's open , it 's positive , but , you know , sometimes when people think of us , the first thing that comes to mind is bio-safety , bio-security , all the dark side stuff . -I 'm not going to minimize those concerns . -Any powerful technology is inherently dual use , and , you know , you get something like synthetic biology , nanobiotechnology , it really compels you , you have to look at both the amateur groups but also the professional groups , because they have better infrastructure , they have better facilities , and they have access to pathogens . -So the United Nations did just that , and they recently issued a report on this whole area , and what they concluded was the power of this technology for positive was much greater than the risk for negative , and they even looked specifically at the DIYbio community , and they noted , not surprisingly , that the press had a tendency to consistently overestimate our capabilities and underestimate our ethics . -As a matter of fact , DIY people from all over the world , America , Europe , got together last year , and we hammered out a common code of ethics . -That 's a lot more than conventional science has done . -Now , we follow state and local regulations . -We dispose of our waste properly , we follow safety procedures , we don 't work with pathogens . -You know , if you 're working with a pathogen , you 're not part of the biohacker community , you 're part of the bioterrorist community , I 'm sorry . -And sometimes people ask me , " Well , what about an accident ? " -Well , working with the safe organisms that we normally work with , the chance of an accident happening with somebody accidentally creating , like , some sort of superbug , that 's literally about as probable as a snowstorm in the middle of the Sahara Desert . -Now , it could happen , but I 'm not going to plan my life around it . -I 've actually chosen to take a different kind of risk . -I signed up for something called the Personal Genome Project . -It 's a study at Harvard where , at the end of the study , they 're going to take my entire genomic sequence , all of my medical information , and my identity , and they 're going to post it online for everyone to see . -There were a lot of risks involved that they talked about during the informed consent portion . -The one I liked the best is , someone could download my sequence , go back to the lab , synthesize some fake Ellen DNA , and plant it at a crime scene . -But like DIYbio , the positive outcomes and the potential for good for a study like that far outweighs the risk . -Now , you might be asking yourself , " Well , you know , what would I do in a biolab ? " -Well , it wasn 't that long ago we were asking , " Well , what would anyone do with a personal computer ? " -So this stuff is just beginning . -We 're only seeing just the tip of the DNA iceberg . -Let me show you what you could do right now . -A biohacker in Germany , a journalist , wanted to know whose dog was leaving little presents on his street ? -Yep , you guessed it . He threw tennis balls to all the neighborhood dogs , analyzed the saliva , identified the dog , and confronted the dog owner . -I discovered an invasive species in my own backyard . -Looked like a ladybug , right ? -It actually is a Japanese beetle . -And the same kind of technology -- it 's called DNA barcoding , it 's really cool -- You can use it to check if your caviar is really beluga , if that sushi is really tuna , or if that goat cheese that you paid so much for is really goat 's . -In a biohacker space , you can analyze your genome for mutations . -You can analyze your breakfast cereal for GMO 's , and you can explore your ancestry . -You can send weather balloons up into the stratosphere , collect microbes , see what 's up there . -You can make a biocensor out of yeast to detect pollutants in water . -You can make some sort of a biofuel cell . -You can do a lot of things . -You can also do an art science project . Some of these are really spectacular , and they look at social , ecological problems from a completely different perspective . -It 's really cool . -Some people ask me , well , why am I involved ? -I could have a perfectly good career in mainstream science . -The thing is , there 's something in these labs that they have to offer society that you can 't find anywhere else . -There 's something sacred about a space where you can work on a project , and you don 't have to justify to anyone that it 's going to make a lot of money , that it 's going to save mankind , or even that it 's feasible . -It just has to follow safety guidelines . -If you had spaces like this all over the world , it could really change the perception of who 's allowed to do biotech . -It 's spaces like these that spawned personal computing . -Why not personal biotech ? -If everyone in this room got involved , who knows what we could do ? -This is such a new area , and as we say back in Brooklyn , you ain 't seen nothin ' yet . -Geert Chatrou : A whistleblower you haven 't heard -In this engaging talk , world champion whistler Geert Chatrou performs the whimsical " Eleonora " by A. Honhoff , and his own " Fête de la Belle . " In a fascinating interlude , he talks about what brought him to the craft . & lt ; em & gt ; & lt ; / em & gt ; -Thank you very much . -That was whistling . -I 'm trying to do this in English . -What is a chubby , curly-haired guy from Holland -- why is he whistling ? -Well actually , I 've [ been ] whistling since the age of four , about four . -My dad was always whistling around the house , and I just thought that 's part of communication in my family . -So I whistled along with him . -And actually , till I was 34 , I always annoyed and irritated people with whistling , because , to be honest , my whistling is a kind of deviant behavior . -I whistled alone . I whistled in the classroom . -I whistled on [ my ] bike . I whistled everywhere . -And I also whistled at a Christmas Eve party with my family-in-law . -And they had some , in my opinion , terrible Christmas music . -And when I hear music that I don 't like , I try to make it better . -So " Rudolph the Red-Nosed Reindeer " -- you know it ? -But it can also sound like this . -But during a Christmas party -- at dinner actually -- it 's very annoying . -So my sister-in-law asked me a few times , " Please stop whistling . " -And I just couldn 't . -And at one point -- and I had some wine , I have to admit that -- at one point I said , " If there was a contest , I would join . " -And two weeks later I received a text message : " You 're going to America . " -So , okay , I 'm going to America . -I would love to , but why ? -So I immediately called her up , of course . -She Googled , and she found this World Whistling Championship in America , of course . -She didn 't expect me to go there . -And I would have lost my face . -I don 't know if that 's correct English . -But the Dutch people here will understand what I mean . -I lost my face . -And she thought , " He will never go there . " -But actually I did . -So I went to Louisburg , North Carolina , southeast United States , and I entered the world of whistling . -And I also entered the world championship , and I won there in 2004 . -That was great fun , of course . -And to defend my title -- like judokas do and sportsmen -- I thought , well let 's go back in 2005 , and I won again . -Then I couldn 't participate for a few years . -And in 2008 I entered again in Japan , Tokyo , and I won again . -So what happened now is I 'm standing here in Rotterdam , in the beautiful city , on a big stage , and I 'm talking about whistling . -And actually I earn my money whistling at the moment . -So I quit my day job as a nurse . -And I try to live my dream -- well , actually , it was never my dream , but it sounds so good . -Okay , I 'm not the only one whistling here . -You say , " Huh , what do you mean ? " -Well actually , you are going to whistle along . -And then always the same thing happens : people are watching each other and think , " Oh , my God . -Why ? Can I go away ? " -No , you can 't . -Actually it 's very simple . -The track that I will whistle is called " Fête de la Belle . " -It 's about 80 minutes long . -No , no , no . It 's four minutes long . -And I want to first rehearse with you your whistling . -So I whistle the tone . -Sorry . I forgot one thing . -You whistle the same tone as me . -I heard a wide variety of tones . -This is very promising . -This is very promising . -I 'll ask the technicians to start the music . -And if it 's started , I just point where you whistle along , and we will see what happens . -Oh , hah . -I 'm so sorry , technicians . -I 'm so used to that . -I start it myself . -Okay , here it is . -Okay . -It 's easy , isn 't it ? -Now comes the solo . I propose I do that myself . -Max Westerman : Geert Chatrou , the World Champion [ of ] Whistling . -Geert Chatrou : Thank you . Thank you . -Roberto D 'Angelo + Francesca Fedeli : In our baby 's illness , a life lesson -Roberto D 'Angelo and Francesca Fedeli thought their baby boy Mario was healthy -- until at 10 days old , they discovered he 'd had a perinatal stroke . With Mario unable to control the left side of his body , they grappled with tough questions : Would he be " normal ? " Could he live a full life ? The poignant story of parents facing their fears -- and how they turned them around . -Francesca Fedeli : Ciao . -So he 's Mario . He 's our son . -He was born two and a half years ago , and I had a pretty tough pregnancy because I had to stay still in a bed for , like , eight months . -But in the end everything seemed to be under control . -So he got the right weight at birth . -He got the right Apgar index . -So we were pretty reassured by this . -But at the end , 10 days later after he was born , we discovered that he had a stroke . -As you might know , a stroke is a brain injury . -A perinatal stroke could be something that can happen during the nine months of pregnancy or just suddenly after the birth , and in his case , as you can see , the right part of his brain has gone . -So the effect that this stroke could have on Mario 's body could be the fact that he couldn 't be able to control the left side of his body . -Just imagine , if you have a computer and a printer and you want to transmit , to input to print out a document , but the printer doesn 't have the right drives , so the same is for Mario . -It 's just like , he would like to move his left side of his body , but he 's not able to transmit the right input to move his left arm and left leg . -So life had to change . -We needed to change our schedule . -We needed to change the impact that this birth had on our life . -As you may imagine , unfortunately , we were not ready . -Nobody taught us how to deal with such kinds of disabilities , and as many questions as possible started to come to our minds . -And that has been really a tough time . -Questions , some basics , like , you know , why did this happen to us ? -And what went wrong ? -Some more tough , like , really , what will be the impact on Mario 's life ? -I mean , at the end , will he be able to work ? -Will he be able to be normal ? -And , you know , as a parent , especially for the first time , why is he not going to be better than us ? -And this , indeed , really is tough to say , but a few months later , we realized that we were really feeling like a failure . -I mean , the only real product of our life , at the end , was a failure . -And you know , it was not a failure for ourselves in itself , but it was a failure that will impact his full life . -Honestly , we went down . -I mean we went really down , but at the end , we started to look at him , and we said , we have to react . -So immediately , as Francesca said , we changed our life . -We started physiotherapy , we started the rehabilitation , and one of the paths that we were following in terms of rehabilitation is the mirror neurons pilot . -Basically , we spent months doing this with Mario . -You have an object , and we showed him how to grab the object . -Now , the theory of mirror neurons simply says that in your brains , exactly now , as you watch me doing this , you are activating exactly the same neurons as if you do the actions . -It looks like this is the leading edge in terms of rehabilitation . -But one day we found that Mario was not looking at our hand . -He was looking at us . -We were his mirror . -And the problem , as you might feel , is that we were down , we were depressed , we were looking at him as a problem , not as a son , not from a positive perspective . -And that day really changed our perspective . -We realized that we had to become a better mirror for Mario . -We restarted from our strengths , and at the same time we restarted from his strengths . -We stopped looking at him as a problem , and we started to look at him as an opportunity to improve . -And really , this was the change , and from our side , we said , " What are our strengths that we really can bring to Mario ? " -And we started from our passions . -I mean , at the end , my wife and myself are quite different , but we have many things in common . -We love to travel , we love music , we love to be in places like this , and we started to bring Mario with us just to show to him the best things that we can show to him . -This short video is from last week . -I am not saying -- — I am not saying it 's a miracle . That 's not the message , because we are just at the beginning of the path . -But we want to share what was the key learning , the key learning that Mario drove to us , and it is to consider what you have as a gift and not only what you miss , and to consider what you miss just as an opportunity . -And this is the message that we want to share with you . -This is why we are here . -Mario ! -And this is why -- — And this is why we decided to share the best mirror in the world with him . -And we thank you so much , all of you . -Thank you . Thank you . Bye . -Thank you . -Mark Shaw : One very dry demo -Mark Shaw demos Ultra-Ever Dry , a liquid-repellent coating that acts as an astonishingly powerful shield against water and water-based materials . At the nano level , the spray covers a surface with an umbrella of air so that water bounces right off . Watch for an exciting two-minute kicker . -I 'm here to show you how something you can 't see can be so much fun to look at . -You 're about to experience a new , available and exciting technology that 's going to make us rethink how we waterproof our lives . -What I have here is a cinder block that we 've coated half with a nanotechnology spray that can be applied to almost any material . -It 's called Ultra-Ever Dry , and when you apply it to any material , it turns into a superhydrophobic shield . -So this is a cinder block , uncoated , and you can see that it 's porous , it absorbs water . -Not anymore . -Porous , nonporous . -So what 's superhydrophobic ? -Superhydrophobic is how we measure a drop of water on a surface . -The rounder it is , the more hydrophobic it is , and if it 's really round , it 's superhydrophobic . -A freshly waxed car , the water molecules slump to about 90 degrees . -A windshield coating is going to give you about 110 degrees . -But what you 're seeing here is 160 to 175 degrees , and anything over 150 is superhydrophobic . -So as part of the demonstration , what I have is a pair of gloves , and we 've coated one of the gloves with the nanotechnology coating , and let 's see if you can tell which one , and I 'll give you a hint . -Did you guess the one that was dry ? -When you have nanotechnology and nanoscience , what 's occurred is that we 're able to now look at atoms and molecules and actually control them for great benefits . -And we 're talking really small here . -The way you measure nanotechnology is in nanometers , and one nanometer is a billionth of a meter , and to put some scale to that , if you had a nanoparticle that was one nanometer thick , and you put it side by side , and you had 50,000 of them , you 'd be the width of a human hair . -So very small , but very useful . -And it 's not just water that this works with . -It 's a lot of water-based materials like concrete , water-based paint , mud , and also some refined oils as well . -You can see the difference . -Moving onto the next demonstration , we 've taken a pane of glass and we 've coated the outside of it , we 've framed it with the nanotechnology coating , and we 're going to pour this green-tinted water inside the middle , and you 're going to see , it 's going to spread out on glass like you 'd normally think it would , except when it hits the coating , it stops , and I can 't even coax it to leave . -It 's that afraid of the water . -So what 's going on here ? What 's happening ? -Well , the surface of the spray coating is actually filled with nanoparticles that form a very rough and craggly surface . -You 'd think it 'd be smooth , but it 's actually not . -And it has billions of interstitial spaces , and those spaces , along with the nanoparticles , reach up and grab the air molecules , and cover the surface with air . -It 's an umbrella of air all across it , and that layer of air is what the water hits , the mud hits , the concrete hits , and it glides right off . -So if I put this inside this water here , you can see a silver reflective coating around it , and that silver reflective coating is the layer of air that 's protecting the water from touching the paddle , and it 's dry . -So what are the applications ? -I mean , many of you right now are probably going through your head . -Everyone that sees this gets excited , and says , " Oh , I could use it for this and this and this . " -The applications in a general sense could be anything that 's anti-wetting . -We 've certainly seen that today . -It could be anything that 's anti-icing , because if you don 't have water , you don 't have ice . -It could be anti-corrosion . -No water , no corrosion . -It could be anti-bacterial . -Without water , the bacteria won 't survive . -And it could be things that need to be self-cleaning as well . -So imagine how something like this could help revolutionize your field of work . -And I 'm going to leave you with one last demonstration , but before I do that , I would like to say thank you , and think small . -It 's going to happen . Wait for it . Wait for it . -You guys didn 't hear about us cutting out the Design from TED ? -[ Two minutes later ... ] He ran into all sorts of problems in terms of managing the medical research part . -It 's happening ! -Dan Ariely : Our buggy moral code -Behavioral economist Dan Ariely studies the bugs in our moral code : the hidden reasons we think it 's OK to cheat or steal . Clever studies help make his point that we 're predictably irrational -- and can be influenced in ways we can 't grasp . -I want to talk to you today a little bit about predictable irrationality . -And my interest in irrational behavior started many years ago in the hospital . -I was burned very badly . -And if you spend a lot of time in hospital , you 'll see a lot of types of irrationalities . -And the one that particularly bothered me in the burn department was the process by which the nurses took the bandage off me . -Now , you must have all taken a Band-Aid off at some point , and you must have wondered what 's the right approach . -Do you rip it off quickly -- short duration but high intensity -- or do you take your Band-Aid off slowly -- you take a long time , but each second is not as painful -- which one of those is the right approach ? -The nurses in my department thought that the right approach was the ripping one , so they would grab hold and they would rip , and they would grab hold and they would rip . -And because I had 70 percent of my body burned , it would take about an hour . -And as you can imagine , I hated that moment of ripping with incredible intensity . -And I would try to reason with them and say , " Why don 't we try something else ? -Why don 't we take it a little longer -- maybe two hours instead of an hour -- and have less of this intensity ? " -And the nurses told me two things . -They told me that they had the right model of the patient -- that they knew what was the right thing to do to minimize my pain -- and they also told me that the word patient doesn 't mean to make suggestions or to interfere or ... -This is not just in Hebrew , by the way . -It 's in every language I 've had experience with so far . -And , you know , there 's not much -- there wasn 't much I could do , and they kept on doing what they were doing . -And about three years later , when I left the hospital , I started studying at the university . -And one of the most interesting lessons I learned was that there is an experimental method that if you have a question you can create a replica of this question in some abstract way , and you can try to examine this question , maybe learn something about the world . -So that 's what I did . -I was still interested in this question of how do you take bandages off burn patients . -So originally I didn 't have much money , so I went to a hardware store and I bought a carpenter 's vice . -And I would bring people to the lab and I would put their finger in it , and I would crunch it a little bit . -And I would crunch it for long periods and short periods , and pain that went up and pain that went down , and with breaks and without breaks -- all kinds of versions of pain . -And when I finished hurting people a little bit , I would ask them , so , how painful was this ? Or , how painful was this ? -Or , if you had to choose between the last two , which one would you choose ? -I kept on doing this for a while . -And then , like all good academic projects , I got more funding . -I moved to sounds , electrical shocks -- I even had a pain suit that I could get people to feel much more pain . diff --git a/neural-machine-translation/vietnam-train b/neural-machine-translation/vietnam-train deleted file mode 100644 index e0775e4..0000000 --- a/neural-machine-translation/vietnam-train +++ /dev/null @@ -1,500 +0,0 @@ -Khoa học đằng sau một tiêu đề về khí hậu -Trong 4 phút , chuyên gia hoá học khí quyển Rachel Pike giới thiệu sơ lược về những nỗ lực khoa học miệt mài đằng sau những tiêu đề táo bạo về biến đổi khí hậu , cùng với đoàn nghiên cứu của mình -- hàng ngàn người đã cống hiến cho dự án này -- một chuyến bay mạo hiểm qua rừng già để tìm kiếm thông tin về một phân tử then chốt . -Tôi muốn cho các bạn biết về sự to lớn của những nỗ lực khoa học đã góp phần làm nên các dòng tít bạn thường thấy trên báo . -Có những dòng trông như thế này khi bàn về biến đổi khí hậu , và như thế này khi nói về chất lượng không khí hay khói bụi . -Cả hai đều là một nhánh của cùng một lĩnh vực trong ngành khoa học khí quyển . -Các tiêu đề gần đây trông như thế này khi Ban Điều hành Biến đổi khí hậu Liên chính phủ , gọi tắt là IPCC đưa ra bài nghiên cứu của họ về hệ thống khí quyển . -Nghiên cứu được viết bởi 620 nhà khoa học từ 40 quốc gia khác nhau . -Họ viết gần 1000 trang về chủ đề này . -Và tất cả các trang đều được xem xét bởi 400 khoa học gia và nhà phê bình khác từ 113 quốc gia . -Đó là cả một cộng đồng lớn , lớn đến nỗi trên thực tế cuộc tụ hội hằng năm của chúng tôi là hội nghị khoa học [ tự nhiên ] lớn nhất thế giới . -Mỗi năm , hơn 15,000 nhà khoa học đến San Francisco để tham dự hội nghị này . -Mỗi một khoa học gia đều thuộc một nhóm nghiên cứu , và mỗi nhóm đều nghiên cứu rất nhiều đề tài đa dạng . -Với chúng tôi , tại Cambridge , các đề tài thay đổi từ sự dao động của El Niño , vốn có tác động đến thời tiết và khí hậu , sự đồng hoá thông tin từ vệ tinh , khí thải từ những cánh đồng nhiên liệu sinh học , tình cờ lại là đề tài tôi nghiên cứu . -Mỗi lĩnh vực nghiên cứu lại chia ra những lĩnh vực nhỏ hơn , và những nghiên cứu sinh có bằng tiến sĩ , như tôi , phải nghiên cứu những đề tài vô cùng cụ thể , cụ thể như chỉ vài quy trình hay vài phân tử . -Một trong số những phân tử tôi nghiên cứu tên là isoprene . Đây . Nó là một phân tử hữu cơ nhỏ . Có thể các bạn cũng chưa từng nghe tên . -Trọng lượng của một chiếc kẹp giấy vào khoảng 900 zeta-illion -- 10 mũ 21 -- phân tử isoprene . -Dù trọng lượng phân tử rất nhỏ , thế nhưng lượng isoprene được thải vào khí quyển hàng năm ngang ngửa với tổng trọng lượng của dân số toàn cầu . -Đó là một lượng khí thải khổng lồ , bằng tổng trọng lượng của mêtan . -Chính vì lượng khí thải rất lớn , nó có ý nghĩa quan trọng với hệ thống khí quyển . -Chính vì nó có ý nghĩa quan trọng với hệ thống khí quyển , giá nào chúng tôi cũng theo đuổi nghiên cứu này đến cùng . -Chúng tôi cho nó nổ và xem xét từng mảnh nhỏ . -Đây là Phòng nghiên cứu khói bụi EUPHORE ở Tây Ban Nha . -Nổ trong không khí hay cháy hoàn toàn diễn ra chậm hơn 15,000 lần so với những phản ứng trong động cơ xe . -Dù vậy , chúng tôi vẫn xem xét từng mảnh nhỏ . -Chúng tôi chạy những mô hình khổng lồ trên siêu máy tính ; đây là công việc của tôi . -Mô hình của chúng tôi gồm hàng trăm ngàn thùng xếp chồng tính toán với hàng trăm biến số trong thời gian cực ngắn . -Mà vẫn cần hàng tuần mới thực hiện xong các phép tích phân . -Chúng tôi cần làm hàng tá phép tính như thế để hiểu được những gì đang xảy ra . -Chúng tôi còn bay khắp thế giới để tìm phân tử này . -Gần đây tôi tham gia một cuộc khảo sát thực địa ở Malaysia . Còn nhiều chuyến khác nữa . -Chúng tôi tìm thấy một tháp canh khí hậu toàn cầu ở đó , ngay giữa rừng sâu , và chúng tôi treo các thiết bị nghiên cứu trị giá hàng trăm ngàn đô la xa khỏi cái tháp để tìm isoprene , và tất nhiên là những thứ khác nữa trong suốt thời gian ở đó . -Đây chính là cái tháp giữa rừng sâu , nhìn từ trên cao . -Và từ dưới đất . -Có giai đoạn chúng tôi còn mang cả máy bay theo . -Chiếc phi cơ này , mẫu BA146 do FAAM sở hữu thông thường có thể chở từ 120-130 người . -Rất có thể bạn đã ở trên một chiếc tương tự khi đến đây hôm nay . -Chúng tôi không chỉ bay . Chúng tôi bay cách tầng vòm của rừng 100 mét để đo đạc phân tử này -- chuyện vô cùng nguy hiểm . -Chúng tôi phải bay với độ nghiêng đặc biệt để thực hiện các phép đo . -Phải thuê quân đội và sát hạch phi cơ để điều khiển máy bay . -Phải xin lệnh đặc biệt cho phép bay . -Khi bay quanh những bờ sông ở thung lũng , các lực tác động có thể lên tới 2G . -Các nhà khoa học phải được thắt chặt hoàn toàn vào ghế để có thể thực hiện đo đạc trên máy bay . -Vì vậy , bạn có thể hình dung , bên trong đó hoàn toàn không giống với bất kỳ chiếc máy bay du lịch nào khác . -Đó là cả một phòng thí nghiệm di động để giúp chúng tôi thực hiện các phép đo . -Chúng tôi làm tất cả chỉ để tìm hiểu tính chất hoá học của một phân tử . -Khi nghiên cứu sinh như tôi có sở thích hay hiểu biết về phân tử đó , đại loại như thế , họ sẽ viết cả một bài nghiên cứu khoa học về đề tài đó . -Và ngoài cuộc khảo sát đó chúng tôi sẽ còn hàng tá bài nghiên cứu về hàng tá các quy trình hay phân tử . -Khi một phần kiến thức dần định hình , nó sẽ tạo thành một tiểu mục , hay một tiểu-tiểu mục trong một bản kiểm định như ở IPCC , mặc dù còn có nhiều bài khác . -Mỗi một chương trong 11 chương của IPCC có từ 6 đến 10 tiểu mục như thế . -Nói như thế để bạn hình dung được quy mô của những nỗ lực này . -Trong mỗi bản đánh giá chúng tôi viết , chúng tôi luôn đính kèm một bản tóm lược , được viết cho những độc giả không chuyên về khoa học . -Chúng tôi đưa bản tóm lược cho các nhà báo và nhà chính sách để có được những dòng tít như thế này . -Cám ơn rất nhiều . -Christopher deCharms quét não bộ theo thời gian thực -Nhà thần kinh học và nhà sáng chế Christopher deCharms cho thấy cách sử dụng fMRI để ghi lại những hoạt động của não bộ -- suy nghĩ , cảm xúc , đau đớn-- ngay khi chúng xảy ra . Nói cách khác , bạn thực sự nhìn thấy những gì bạn cảm nhận . -Xin chào . Tôi đề nghị các bạn giơ tay và vẫy về phía sau như tôi làm đây -- như cách vẫy hoàng gia . -Bắt chước những gì bạn nhìn thấy . -Bạn có thể lập trình cho hàng trăm cơ bắp trong cánh tay . -Bạn sẽ sớm nhìn được vào bên trong não bộ , điều khiển hàng trăm vùng trên não mà bạn thấy đó . -Tôi sẽ cho bạn biết về công nghệ đó . -Con người muốn nhìn được vào bên trong ý nghĩ , não người , qua hàng ngàn năm nay , -Vâng , bước ra khỏi phòng thì nghiệm có vẻ như là cách thế hệ chúng ta giải quyết việc đó . -Con người tưởng tượng điều này sẽ rất khó . -Bạn sẽ phải thu nhỏ một chiếc phi thuyền , đưa vào trong mạch máu . -Điều này thực sự nguy hiểm . -bạn có thể bị các bạch cầu tấn công trong động mạch . -Nhưng bây giờ , chúng ta có một công nghệ thực để làm việc này . -Chúng ta sẽ bay vào trong não của đồng nghiệp của tôi , Peter . -Chúng ta sẽ làm điều này mà không xâm nhập bên trong , sử dụng MRI . -Không cần bơm thứ gì vào . Không cần đến tia bức xạ . -Chúng ta sẽ có thể bay vào hộp sọ của não Peter -- theo nghĩa đen là bay vào cơ thể anh ta -- nhưng quan trọng hơn , ta có thể nhìn vào tâm trí của anh ta . -Khi Peter di chuyển cánh tay , chấm màu vàng mà bạn thấy ở đó là bề mặt mà ý thức của Peter hoạt động -Trước đó bạn đã thấy là với các điện cực ta có thể điều khiển cánh tay robot , và ảnh chụp não bộ và máy quét có thể cho thấy bên trong của não . -Cái mới chính là quá trình đã từng chiếm nhiều ngày hoặc nhiều tháng để phân tích . -Chúng ta đã đạt được điều này qua công nghệ đến mức mili-giây. và điều này cho phép Peter nhìn thấy não bộ anh ấy dưới thời gian thực khi anh ta ở trong máy quét . -Anh ta có thể thấy 65000 điểm kích hoạt trên 1 giây . -Nếu thấy được mẫu này của não bộ , anh ta có thể học cách điều khiển nó . -Có ba cách để làm ảnh hưởng đến não : giường của nhà trị liệu học , thuốc viên và con dao . -Đây là lụa chọn thứ tư mà bạn sẽ nhanh chóng có . -Ta đều biết rằng khi suy nghĩ , ta đã tạo ra những kênh nằm sâu trong tâm trí và trong não . -Đau kinh niên là một ví dụ . Nếu bạn phỏng , bạn sẽ giật tay ra xa . -Nhưng nếu trong sáu tháng , hay sáu năm , cơn đau vẫn không dứt , đó là vì những vòng tuần hoàn này đang sản xuất ra cơn đau chống lại bạn . -Nếu ta có thể nhìn vào các xung kích hoạt của não sản xuất ra cơn đau , ta có thể lập ra các mô hình 3 chiều và nhìn thấy các thông tin quá trình của não theo thời gian thực , chúng ta có thể lựa chọn vùng sản xuất cơn đau . -Vâng , hãy giơ tay lên và cong cơ cánh tay lại . -Bây giờ hãy tưởng tượng bạn sớm được nhìn vào bên trong não mình và được chọn vùng trên não để làm cùng một việc đó . -Và điều bạn thấy là , Chúng ta đã chọn đường đi trong não bộ của một bệnh nhân đau kinh niên . -Điều này có thể làm bạn shock , nhưng thực sự chúng ta đã đọc được não bộ của người này theo thời gian thực . -Họ đang theo dõi hoạt động não bộ của chính họ , và điều khiển con đường gây nên cơn đau . -Họ tập co dãn hệ thống tiết ra chất xoa dịu từ bên trong . -Khi họ làm vậy , ở góc trên bên trái ta thấy được thứ đã kết nối kích hoạt não bộ của cơn đau đang được điều khiển của họ . -Khi họ điều khiển não bộ , họ điều khiển cơn đau của mình . -Đây là một phương pháp thử nghiệm , nhưng trong các phép thử chúng ta đã thấy lượng bệnh nhân đau kinh niên giảm 44-64 % . -Đây không phải là " Ma trận . " Bạn chỉ có thể làm điều này với chính bản thân mình . Bạn tự làm chủ . -Tôi đã nhìn vào trong não mình . Bạn cũng sớm làm như vậy thôi . -Khi bạn làm được , bạn muốn điều khiển cái gì ? -Bạn có thể nhìn vào mọi phương diện khiến bạn là chính mình , tất cả những kí ức . -Đây là một trong số những vấn đề chúng ta nói đến hôm nay mà tôi không có thời gian để đi vào chi tiết . -Nhưng tôi có một câu hỏi lớn dành cho bạn . -Chúng ta là thế hệ đầu tiên có thể bước vào , sử dụng công nghệ này , trí tuệ con người và não bộ , -Chúng ta sẽ đưa nó đến đâu ? -Beeban Kidron : Đìều kì diệu của điện ảnh -Những bộ phim có sức mạnh tạo nên những kinh nghiệm tường thuật được chia sẻ và định hình những kí ức và những cách nhìn thế giới . Nhà đạo diễn phim người Anh - Beeban Kidron dẫn chứng bằng những cảnh phim hình tượng -- từ " Phép màu ở Milan " đến " Những câu bé và khu dân cư " -- khi bà kể cách mà nhóm FILMCLUB của bà chia sẻ những thước phim vĩ đại với lũ trẻ . -Bằng chứng cho thấy rằng con người ở mọi lứa tuổi và từ mọi nền văn hoá tạo ra danh tính của họ theo một dạng tường thuật nào đó . -Từ mẹ đến con gái , người thuyết giáo đến người theo hội , giáo viên đến học sinh , người kể chuyện đến khán thính giả . -Bất kể ở các hình vẽ trong hang động hay các cách dùng mới nhất của Internet , con người luôn kể câu chuyện lịch sử và về những sự thật qua dụ ngôn và chuyện tưởng tượng -Chúng ta là những người kể chuyện bản năng . -Nhưng ở đâu , trong thế giới già nhanh chóng già cỗi và chia nhỏ của chúng ta , chúng ta trao tặng những kinh nghiệm mang tính cộng đồng , không qua trung gian bởi quyền lợi tiêu dùng kịch liệt của chính chúng ta ? -Và chuyện tường thuật nào , lịch sử nào , bản sắc nào , qui tắc đạo đức nào mà chúng ta đang truyền đạt lại cho thế hệ trẻ của chúng ta ? -Điện ảnh đáng được tranh cãi là dạng nghệ thuật ảnh hưởng nhất trong thế kỉ 20 . -Nó là những câu chuyện kể của các nghệ sĩ vượt qua các ranh giới quốc gia , dưới vô vàn ngôn ngữ , thể loại và triết lý mà một người có thể tưởng tượng ra được . -Thực sự là , thật khó để tìm một chủ đề mà điện ảnh chưa động đến . -Trong suốt thập kỉ qua chúng ta đang chứng kiến sự hội nhập rộng lớn của phương tiện truyền thông toàn cầu , giờ bị thống trị bởi văn hoá phim bom tấn Hollywood . -Chúng ta đang được phục vụ một chế độ " ăn kiêng " mà sự cảm giác là chủ chốt , chứ không phải nội dung . -Điều gì đã quen thuộc với tất cả chúng ta 40 năm trước -- việc kể các câu chuyện giữa các thế hệ-- bây giờ rất hiếm hoi . -Là một nhà làm phim , điều đó làm tôi lo ngại . -Là một con người , nó reo sự sợ hãi của Chúa vào tôi . -Tương lai nào những con người trẻ có thể xây dựng với những nắm bắt quá nhỏ bé về nơi họ sinh ra và quá ít những câu chuyện tường thuật về chuyện gì là có thể ? -Thật quá mỉa mai ; cơ hội nắm bắt kĩ thuật chưa bao giờ lớn hơn thế , cơ hội nắm bắt văn hoá chưa bao giờ yếu hơn thế . -Và vì vậy vào năm 2006 chúng tôi lập FILMCLUB , một tổ chức định kì hàng tuần chiếu phim trong các trường học và sau đó là các cuộc thảo luận . -Nếu chúng ta có thể tra soát biên niên sử 100 năm của phim , có lẽ chúng ta có thể xây dựng một chuyện tường thuật mang ý nghĩa đến thế giới phân mảnh và không ngừng nghỉ của thế hệ trẻ . -Được tiếp xúc với công nghệ , ngay cả trường học ở một thôn ngoại thành nhỏ bé có thể chiếu một DVD lên một bảng trắng . -Trong 9 tháng đầu tiên chúng tôi cho chạy 25 câu lạc bộ dọc nước Anh , cho những nhóm trẻ em từ 5 đến 18 tuổi xem một bộ phim không bị ngắt quãng trong 90 phút . -Những bộ phim được biên đạo và bối cảnh hoá . -Nhưng sự lựa chọn thuộc về chúng , và khán thính giả của chúng tôi tăng lên nhanh chóng để chọn những món " ăn kiêng " giàu nhất và đa dạng nhất mà chúng tôi có thể cung cấp . -Có kết quả ngay lập tức . -Đó là cách giáo dục thâm tuý và có khả năng truyền tải nhất . -Một nhóm có tối đa 150 và tối thiểu 3 người , những bạn trẻ này khám phá những nơi mới , những suy nghĩ mới , những góc nhìn mới . -Ngay khi thử nghiệm kết thúc , chúng ta đã có tên của hàng ngàn trường học mong muốn được tham gia . -Bộ phim đã thay đổi cuộc đời của tôi là bộ phim năm 1951 của Vittorio De Sica , " Phép màu ở Milan " . -Đó là một lời nhận xét đáng chú ý trong những khu ổ chuột , nghèo đói và khát vọng . -Tôi đã xem bộ phim vào dịp sinh nhật lần thứ 50 của bố tôi . -Công nghệ lúc đó đã khiến chúng ta phải thuê một rạp để xem , tìm và trả cho việc in tráng và người chiếu phim . -Nhưng với cha của tôi , Sự quan trọng của cảm xúc và tính nghệ thuật trong cách nhìn của De Sica là rất lớn đến nỗi ông chọn nó để ăn mừng sinh nhật thứ 50 của mình với ba đứa con tuổi teen và 30 người bạn của chúng , " Để , " ông nói , truyền sự quan tâm và niềm hy vọng cho thế hệ tiếp theo . " -Trong cảnh cuối của " Phép màu ở Milan " những người trong khu ổ chuột đã nổi lên bầu trời trên những cây chổi bay . -Sáu mươi năm sau khi bộ phim được làm ra và 30 năm sau lần đầu tiên tôi xem nó , tôi thấy những gương mặt trẻ nghiêng lên trong sự kinh ngạc nỗi nghi ngờ của chúng hợp với nỗi nghi ngờ của tôi . -Và tốc độ mà chúng liên hệ nó với " Triệu phú khu ổ chuột " hay những khu phố " favela " ở Rio nói lên bản chất bền vững đó . -Trong mùa chiếu của Câu lạc bộ phim về dân chủ và chính quyền , chúng tôi đã chiếu " Ông Smith đến Washington . " -Được làm vào năm 1939 , bộ phim có tuổi già hơn tuổi của hầu hết ông bà của các thành viên -Sự cổ điển của Frank Capra có giá trị ở tính độc lập và sự thích nghi . -Bộ phim chỉ ra làm thế nào để làm đúng , làm thế nào để trở nên kì lạ phi thường . -Nó cũng là cách diễn tả về lòng tin coi bộ máy chính trị như nguồn gốc danh dự . -Không lâu sau đó " Ông Smith " trở thành bộ phim kinh điển của Câu lạc bộ phim , Có một tuần tất cả các buổi tối " cản trở lại các luật lệ " ở Toà nhà Nhà cầm quyền . -và thật vui vô cùng khi chúng tôi thấy những bạn trẻ trên khắp đất nước giải thích với nhà cầm quyền rằng cản trở các đạo luật là gì và tại sao các nhà cầm quyền có thể định giờ ngủ của họ theo một nguyên tắc nào đó . -Nói chung thi Jimmy Stewart đã cản trở các đạo luật trong toàn bộ 2 bộ phim cơ mà . -Bằng cách chọn " Khách sạn Rwanda " bọn trẻ đã khám phá về tôi diệt chủng ở dạng thú tính nhất . -Nó gây ra những giọt nước mắt và khơi gợi những câu hỏi thâm thuý về những đội quân bảo vệ hoà bình không vũ khí và sự lừa gạt của xã hội phương tây khi đối diện với cuộc đấu tranh đạo đức với những tiện nghi thực dụng trong đầu -Và khi " Bản danh sách của Schindler " khiến bọn trẻ không bao giờ quên , một đứa trẻ , với đầy sự đau đớn tỉnh táo , nhận xét rằng , " Chúng ta đã quên mất rồi , nếu không thì làm thế nào mà " Khách sạn Rwanda " lại xảy ra ? " -Khi bọn trẻ xem nhiều phim hơn , cuộc sống của chúng phong phú hơn . -" Kẻ móc túi " bắt đầu một cuộc tranh cãi về việc tước quyền công dân của tội phạm . -" Gửi ngài , với sự yêu mến " đốt cháy khán giả tuổi thành niên của bộ phim . -Chúng ăn mừng sự thay đổi về thái độ đối với những người Briton không phải da trắng , nhưng chửi rủa hệ thống trường học không ngơi nghỉ của họ không có giá trị bản sắc cộng đồng , không giống như sự giám hộ cẩn trọng của Sidney Potier mang lại . -giờ đây , những đứa trẻ sâu sắc , có chính kiến và tò mò này không nghĩ gì ngoài việc nắm lấy những bộ phim -- đen trắng , phụ đề , tài liệu , phi tường thuật hay tưởng tượng -- và không nghĩ gì về viết những bài nhân xét chi tiết tranh đua nói về những bộ phim yêu thích bằng những bài văn xuôi đam mê và càng ngày càng triết lý . -6000 bản nhận xét mỗi tuần ở từng trường ganh đua cho sự vinh dự được thành bài nhận xét của tuần . -Từ 25 câu lạc bộ , chúng tôi đã có hàng trăm , rồi hàng ngàn , cho đến khi chúng tôi có gần một phần tư triệu đứa trẻ trong 7,000 câu lạc bộ dọc đất nước . -Mặc dù những con số đó đã , và tiếp tục tăng một cách đáng kinh ngạc , điều đã trở nên kinh ngạc hơn nữa là làm thế nào sự trải nghiệm về những câu hỏi phê bình tò mò được chuyển tải vào cuộc sống . -Một vài đứa trẻ của chúng tôi đã bắt đầu nói chuyện với bố mẹ chúng , một số nói với giáo viên , hoặc bạn bè của chúng . -Và với những em không có bạn , bắt đầu kết bạn . -Những bộ phim đem lại sự liên kết ở tất cả những dạng bị chia cắt . -Và các câu chuyện , chúng đã giúp cung cấp những kinh nghiệm mang tính chia sẻ . -" Persepolis " mang một bé gái đến gần hơn với người mẹ Iran của mình và " Hàm cá mập " trở thành cách mà một câu bé nhỏ tuổi có thể nói lên nỗi sợ mà cậu đã trải qua về bạo lực trong một chuyến bay đã giết chết đầu tiên là bố rồi đến cả mẹ của cậu , mẹ cậu đã bị ném qua mạn tàu trong một chuyến đi tàu -Ai đã đúng , ai sai ? -Họ sẽ làm gì nếu bị đặt dưới tình trạng tương tự ? -Câu chuyện kể có hay không ? -Có thông điệp ẩn dấu nào trong đó ? -Làm thế nào thế giới thay đổi ? Làm thế nào nó có thể khác đi ? -Cơn bão các câu hỏi đã được bay tới tấp từ miệng của những đứa trẻ những người mà thế giới từng nghĩ sẽ chẳng quan tâm -Và chúng không tự biết rằng chúng quan tâm . -Và khi chúng viết và tranh luận , hơn là thấy những bộ phim như là những tạo tác , chúng bắt đầu nhìn thấy bản thân . -Tôi có một người cô là một người kể chuyện tuyệt vời . -Trong một lúc cô có thể đánh thức những hình ảnh như chạy chân trần trên núi Bàn và chơi trò cảnh sát và kẻ cướp . -Khá gần đây cô có bảo tôi rằng vào năm 1948 , hai trong số người chị em của cô và bố tôi đã du lịch trên một chiếc thuyền đến Israel mà không có ông bà tôi . -Khi đoàn thuỷ thủ nổi loạn trên biển vì nhu cầu thiết yếu của con người chính là những thiếu niên này đã cho đoàn thuỷ thủ ăn . -Tôi đã hơn 40 khi bố tôi mất . -Ông không bao giờ đề cập đến chuyến đi đó . -Mẹ của mẹ tôi đã rời khỏi châu Âu trong một nạn đói mà không có chồng của bà , nhưng với đứa con gái 3 tuổi và kim cương khâu viền trên váy . -Sau 2 năm lẩn trốn , ông tôi xuất hiện ở Luân Đôn . -Ông đã không bao giờ đúng nữa . -Và câu chuyện của ông đi vào im lặng khi ông bị đồng hoá . -Câu chuyện của tôi bắt đầu ở nước Anh với lý lịch tạm trong sạch và sự im lặng của bố mẹ là người nhập cư . -Tôi có " Anne Frank " , " Sự trốn thoát vĩ đại " , " Shoah " , " Chiến thắng của nhà Will " -Đó là Leni Riefenstahl trong ngôi chùa Nazi tao nhã tạo ra bối cảnh mà gia đình đó phải chịu đựng . -Những bộ phim này mang đến nỗi đau quá lớn đến không nói nổi thành lời và chúng trở nên hữu ích cho tôi hơn hàng ngàn lời thì thầm của những người sống sót và cái nhìn thoáng qua không thường xuyên vào hình xăm trên cánh tay người cô -Người theo chủ nghĩa thuần tuý có lẽ cảm thấy rằng sự giả tưởng xua tan nhu cầu hiểu thật sự của con người rằng phim quá thô thiển để nói về những câu chuyện phức tạp và chi tiết , hay những nhà làm phim luôn phục vụ sự cường điệu hơn là sự thật . -Nhưng trong những cuộn phim là mục đích và ý nghĩa -Như một đứa trẻ 12 tuổi nói sau khi xem " Phù thuỷ xứ Oz " " Mọi người nên xem phim này , bới vì nếu không xem mọi người sẽ có thể không biết mình cũng có trái tim " -Chúng ta xem trọng việc đọc sách , tại sao không xem trọng việc xem phim với niềm đam mê ? -Hãy xem " Công dân Kane " có giá trị như Jane Austen . -Hãy đồng ý rằng " Những cậu bé và khu dân cư " giống như Tennyson , đem lại khung cảnh xúc động và sự thấu hiểu cao độ rằng chúng phối hợp được với nhau . -mỗi một mảnh của nghệ thuật đáng nhớ , mỗi một viên gạch của bức tường về chúng ta là ai . -Và được thôi nếu chúng ta nhớ Tom Hanks hơn nhà du hành vũ trụ Jim Lovell hay đặt khuôn mặt của Ben Kíngléy chồng lên mặt của Gandhi -Và dù không có thật , Eve Harrington , Howard Beale , Mildred Pierce là cơ hội để khám phá là con người thì như thế nào và không hề bớt hữu ích khi hiểu về cuộc sống và thời gian của chúng ta như Shakespeare rọi sáng thế giới của Elizabeth nước Anh . -Chúng ta đoán rằng phim , nơi những câu chuyện là nơi hội tụ của kịch tích , âm nhạc , văn học , kinh nghiệm con người , có thể tham gia truyền nguồn cảm hứng cho những đứa trẻ tham gia trong FILMCLUB , -Cái mà chúng tôi không nhìn thấy trước được là sự phát triển có thể đo đạc được trong hành vi , sự tự tin và kết quả học tập . -Những học sinh từng miễn cưỡng giờ đây đến trường , nói chuyện với giáo viên của họ , đánh nhau , không phải ở sân chơi , mà là để chọn bộ phim chiếu vào tuần tới -- những đứa trẻ tìm thấy được định nghĩa bản thân , sự tham vọng và muốn học và tham gia vào cộng đồng từ những câu chuyện chúng xem . -Thành viên của chúng tôi thách thức sự mô tả nhị phân về cách mà chúng ta thường mô tả những đứa trẻ của chúng ta . -Chúng không hoang dã hay tập trung quá nhiều vào bản thân . -Chúng như những đứa trẻ khác , đang thương lượng với thế giới về sự lựa chọn vô cùng , nhưng lại là một văn hoá bé nhỏ về cách để có một trải nghiệm có ý nghĩa -Chúng tôi ngạc nhiên trước những hành vi của những đứa trẻ tự định nghĩa mình bằng cỡ nấc giày , những gì thu nhận được có tính chất tường thuật mà chúng tôi đem lại . -Nếu chúng ta muốn những giá trị khác chúng ta phải kể một câu chuỵện khác , một câu chuyện hiểu được rằng một dạng tường thuật cá nhân là một thành phần cần thiết của một cá thể con người , và một dạng tường thuật tập thể là cần thành phần thiết cho một bản sắc văn hoá , và không có nó thì thật không thể tưởng tượng được bản thân là một phần của tập thể . -Bởi khi những đứa trẻ này về nhà sau khi xem xong " Cửa sổ kì lạ " và đưa ánh nhìn của chúng vào toà nhà bên cạnh , chúng có những công cụ để tự hỏi , ngoài chúng ta có ai ngoài kia và câu chuyện của họ là gì . -Cảm ơn các bạn . -Ellen Jorgensen : Hack sinh học -- bạn cũng có thể làm được việc đó . -Chúng ta đã có máy tính cá nhân , tại sao không phải là công nghệ sinh học cá nhân ? Đó là điều mà nhà sinh vật học Ellen Jorgensen và cộng sự của bà tự hỏi khi lập ra Genspace , một phòng thí nghiệm sinh học phi lợi nhuận ở Brooklyn dành cho khoa học cộng đồng , nơi mà những người nghiệp dư có thể đến với công nghệ sinh học . Khác xa so với phòng thí nghiệm xấu xa của Frankenstein , Genspace cung cấp một danh sách dài những lợi ích vui nhộn , sáng tạo và thiết thực của DIYbio . -Thời đại này rất tuyệt để làm một nhà sinh học phân tử . -Việc đọc và viết trình tự DNA đang trở nên dễ dàng hơn và rẻ hơn . -Đến cuối năm nay , chúng ta sẽ có thể giải trình tự của 3 triệu mã thông tin từ bộ gen của mình trong vòng một ngày với giá ít hơn 1 ngàn euro . -Công nghệ sinh học có lẽ là ngành công nghệ mạnh nhất và phát triển nhanh nhất . -Nó có tiềm năng để thay thế nhiên liệu hoá thạch , cách mạng hoá y học , và ảnh hưởng đến mọi khía cạnh của cuộc sống hằng ngày của chúng ta . -Vậy ai là người sẽ thực hiện nó ? -Tôi nghĩ tất cả chúng ta đều khá yên tâm khi người này làm việc đó . -Nhưng còn người này thì sao ? -Vào năm 2009 , tôi lần đầu tiên biết đến DIYbio . -Đó là một phong trào khuyến khích đưa công nghệ sinh học đến với tất cả mọi người , không chỉ với các nhà khoa học và những người trong phòng thí nghiệm của chính phủ . -Ý tưởng ở đây là nếu chúng ta mở rộng cánh cửa khoa học và cho phép nhiều nhóm người khác nhau tham gia , nó sẽ thúc đẩy sự sáng tạo . -Đưa công nghệ vào tay những người sử dụng thường là một ý tưởng tốt vì họ biết rõ nhất về nhu cầu của chính họ . -Đây là một công nghệ tinh vi đi cùng với nó là những câu hỏi về mặt xã hội , đạo đức và đạo lý , và các nhà khoa học thì rất dở trong việc giải thích với công chúng một cách chính xác họ đang làm gì trong phòng thí nghiệm . -Do đó , phải chăng sẽ tốt hơn nếu có một nơi gần nhà mà bạn có thể đến và tìm hiểu về những điều này , và tự tay làm ? -Tôi nghĩ là tốt . -Nên 3 năm trước , tôi cùng với vài người bạn cùng chung lý tưởng lập nên Genspace . -Đó là một phòng thí nghiệm công nghệ sinh học cho cộng đồng và phi lợi nhuận , tại Brooklyn , New York , với ý tưởng là mọi người có thể đến , để tham dự những lớp học và " vọc " trong phòng thí nghiệm trong một môi trường cởi mở và thân thiện . -Không một kinh nghiệm nào trước đây có thể giúp tôi chuẩn bị cho những gì xảy ra sau đó . Bạn có thể đoán được không ? -Báo giới bắt đầu gọi chúng tôi . -Và chúng tôi càng nói về lợi ích của việc tăng sự hiểu biết về khoa học , thì họ lại càng muốn nói về việc chúng tôi đang tạo ra một Frankenstein mới , và kết quả là , trong vòng 6 tháng sau đó , khi bạn google tên tôi , thay vì tìm thấy những bài báo khoa học của tôi , bạn tìm được : -[ Tôi có phải là hiểm hoạ sinh học ? ] Việc đó thật đáng buồn . -Điều duy nhất giúp chúng tôi vượt qua giai đoạn đó là chúng tôi biết rằng trên toàn thế giới , có nhiều người cũng đang cố gắng làm cùng việc mà chúng tôi đang làm . -Họ cũng mở những nơi dành cho hacker sinh học , và một số còn phải đối mặt với những thử thách lớn hơn chúng tôi , nhiều quy định hơn và ít tài nguyên hơn . -Nhưng giờ đây , ba năm sau , đây là thành quả của chúng tôi . -Một không gian sôi động dành cho cộng đồng hacker sinh học toàn thế giới , và đây chỉ là bước đầu . -Đây là một trong những cộng đồng lớn nhất , và có nhiều nơi khác đang mở cửa hằng ngày . -Có một chỗ có lẽ sắp mở cửa ở Moscow , một ở Hàn Quốc , và điều thú vị là mỗi nơi đều có đặc điểm riêng của mình được phát triển dựa trên cộng đồng của họ . -Hãy để tôi đưa các bạn thăm quan một chút . -Những hacker sinh học làm việc đơn lẻ . -Chúng tôi làm việc theo nhóm , trong những thành phố lớn - - và trong những ngôi làng nhỏ . -Chúng tôi tự chế dụng cụ phòng thí nghiệm . -Chúng tôi áp dụng kỹ thuật di truyền trên vi khuẩn . -Chúng tôi hack phần cứng , phần mềm , phần ướt , và dĩ nhiên hack luôn mã sinh học . -Chúng tôi thích xây dựng mọi thứ . -Sau đó chúng tôi lại thích tháo rời mọi thứ ra . -Chúng tôi làm cho nhiều thứ phát triển . -Chúng tôi làm cho nhiều thứ phát sáng . -Và chúng tôi còn làm cho tế bào nhảy múa . -Tinh thần của những phòng thí nghiệm này là cởi mở và tích cực , nhưng đôi lúc khi người ta nghĩ đến chúng tôi , thì điều đầu tiên họ nghĩ đến là an toàn sinh học , an ninh sinh học và những điều đen tối khác . -Tôi sẽ không coi thường những quan ngại này . -Bất kì kỹ thuật nào cũng như con dao hai lưỡi , và , bạn biết rằng , khi bạn có những thứ như sinh học tổng hợp , công nghệ sinh học nano , bạn buộc phải nhìn vào không chỉ những nhóm nghiệp dư mà cả những nhóm chuyên nghiệp , vì họ có cơ sở hạ tầng tốt hơn , họ có điều kiện thuận lợi hơn , và họ có thể tiếp cận các tác nhân gây bệnh . -Vậy Liên Hiệp Quốc đã làm đúng như vậy , và gần đây họ làm một báo cáo trên toàn lĩnh vực này , và điều họ kết luận là sức mạnh tích cực của công nghệ này lớn hơn nhiều những sự mạo hiểm tiêu cực , và họ thậm chí còn đặc biệt xem xét cộng đồng DIYbio , và họ ghi chú rằng , không đáng ngạc nhiên lắm , báo chí có xu hướng đánh giá cao khả năng của chúng ta và đánh giá thấp đạo đức của chúng ta . -Sự thật là , thành viên DYI từ khắp thế giới , Mỹ , Châu Âu , tụ tập lại vào năm ngoái , và chúng tôi đặt ra một bộ luật đạo đức chung . -Và nó nhiều hơn rất nhiều những gì khoa học thông thường đã làm được . -Giờ đây , chúng tôi tuân thủ luật pháp của bang và luật địa phương . -Chúng tôi xử lí rác thải một cách hợp lí , chúng tôi tuân thủ các quy trình an toàn , chúng tôi không làm việc với những tác nhân gây bệnh . -Bạn thấy đấy , nếu bạn đang làm việc với tác nhân gây bệnh , thì bạn không nằm trong cộng đồng của chúng tôi , bạn nằm trong cộng đồng khủng bố sinh học , tôi xin lỗi . -Và đôi khi có người hỏi tôi , " Vậy nếu có tai nạn thì sao ? " -À , làm việc với những sinh vật an toàn như chúng tôi thường tiếp xúc thì khả năng xảy ra tai nạn , ví dụ như người nào đó vô tình tạo ra một loại siêu bọ , khả năng này cũng tương đương như khả năng một trận bão tuyết xảy ra giữa sa mạc Sahara . -Nó có thể xảy ra , nhưng tôi không có ý định để đời tôi phụ thuộc vào khả năng đó . -Thật ra tôi đã chọn một loại mạo hiểm khác . -Tôi đăng kí một chương trình gọi là Dự Án Gen Cá Nhân . -Đó là một nghiên cứu ở Havard mà khi kết thúc , họ sẽ lấy toàn bộ trình tự gen của tôi , toàn bộ thông tin y học của tôi , và nhận dạng của tôi , và họ sẽ đăng nó lên mạng cho mọi người thấy . -Có rất nhiều nguy cơ liên quan mà họ nói đến trong phần thông báo sự chấp thuận . -Điều mà tôi thích nhất là , ai đó có thể tải trình tự gen của tôi xuống , trở lại phòng thí nghiệm , tổng hợp một số ADN giả và đặt nó tại hiện trường một vụ án . -Nhưng giống như DIYbio , kết quả tích cực và tiềm năng tốt của một nghiên cứu như vậy lớn hơn sự mạo hiểm rất nhiều . -Bây giờ , có thể bạn đang tự hỏi , " Bạn biết không , tôi sẽ làm gì trong một phòng thí nghiệm sinh học ? " -À , không lâu trước đây chúng ta từng tự hỏi , " Nào , ai sẽ làm được gì với một chiếc máy tính cá nhân chứ ? " . -Vậy đây chỉ mới là sự bắt đầu . -Chúng ta chỉ mới thấy đỉnh của tảng băng DNA . -Để tôi cho bạn thấy bạn có thể làm gì ngay bây giờ . -Một nhà biohacker người Đức , một nhà báo , muốn biết chó của ai đã để lại những " món quà " nho nhỏ trên đường ? -Phải , bạn đã đoán ra . Ông ta quăng quả banh quần vợt vào tất cả các con chó trong khu phố , phân tích nước bọt , xác định con chó , và đối chất với chủ của con chó . -Tôi phát hiện ra một loài sinh vật đã xâm lược sân sau nhà tôi . -Trông như một con bọ hung nhỉ ? -Thật ra nó là một con bọ cánh cứng Nhật Bản . -Và cũng loại công nghệ đó -- được gọi là mã vạch ADN , nó thật sự tuyệt vời -- Bạn có thể dùng nó để kiểm tra xem trứng cá muối của bạn có thật là từ cá tầm không , xem miếng sushi đó có thật là cá ngừ không , hoặc pho mát dê mà bạn mua rất đắt đó có thật là từ dê không . -Trong không gian của một nhà biohacker , bạn có thể phân tích gen của bạn để tìm đột biến . -Bạn có thể phân tích ngũ cốc của bạn để tìm thực phẩm biến đổi gen , và bạn có thể khám phá tổ tiên của mình . -Bạn có thể thả khí cầu thời tiết lên tầng tĩnh khí , thu thập vi khuẩn , xem điều gì đang xảy ra trên đó . -Bạn có thể làm ra một dụng cụ kiểm duyệt sinh học từ men để phát hiện chất gây ô nhiễm trong nước . -Bạn có thể làm ra một loại pin nhiên liệu sinh học . -Bạn có thể làm rất nhiều thứ . -Bạn còn có thể thực hiện các dự án khoa học nghệ thuật . Một vài trong số đó thật sự rất ngoạn mục , và chúng nhìn nhận các vấn đề xã hội và sinh thái từ một góc nhìn hoàn toàn khác biệt . -Điều đó thật sự rất tuyệt . -Vài người hỏi tôi , à , tại sao tôi lại tham gia vào việc này ? -Tôi có thể có một sự nghiệp hoàn hảo trong các ngành khoa học chính . -Vấn đề là , có một điều gì đó trong các phòng thí nghiệm này mà bạn không thể tìm thấy ở bất cứ nơi nào khác . -Có một điều gì đó thiêng liêng về nơi mà bạn có thể thực hiện một dự án , và bạn không phải biện minh với bất kì ai rằng nó sẽ đem về rất nhiều tiền , rằng nó sẽ cứu nhân loại , hoặc thậm chí là nó có thể thực hiện được . -Nó chỉ cần tuân thủ những quy tắc an toàn . -Nếu bạn có những không gian như thế này trên toàn thế giới , nó sẽ thật sự thay đổi nhận định về việc ai được phép làm công nghệ sinh học . -Chính những nơi như thế này đã sản sinh ra máy tính cá nhân . -Vậy sao không phải là công nghệ sinh học cá nhân ? -Nếu mọi người trong phòng này đều tham gia , ai mà biết được chúng ta có thể làm những gì ? -Đây là một lĩnh vực rất mới , và như chúng tôi nói ở Brooklyn , bạn còn chưa thấy gì cả đâu . . -Một người huýt gió bạn chưa từng biết đến -Tại TEDxRotterdam , nhà quán quân thổi sáo thế giới Geert Chatrou biểu diễn bài " Eleonora " của A.Honhoff , và bài " Fête de la Belle " do ông tự sáng tác . Trong , ông ấy trò chuyện về cái mà đã thôi thúc ông đến với thổi sáo . -Cám ơn rất nhiều -Đó là huýt sáo -Tôi đang cố huyết sáo bằng tiếng Anh -Người đàn ông tròn trịa , tóc xoăn đến từ Hà Lan này là ai -- tại sao ông ấy lại huýt sáo ? -Thực ra , tôi huýt gió kể từ khi tôi bốn tuổi -- khoảng tầm bốn tuổi -Bố tôi từng lúc nào cũng huýt gió khắp nơi trong nhà and tôi cứ ngỡ đó là một phần trong cách giao tiếp của gia đình tôi . -Vì vậy tôi huýt gió cùng với ông ấy . -Và thậm chí cho đến khi tôi 34 tuổi , lúc nào tôi cũng quấy rầy và khiến mọi người khó chịu với việc huýt sáo của mình . Bởi vì , thành thật mà nói , huýt gió có thể coi là một tật xấu của tôi . -Tôi huýt gió một mình , tôi huýt gió trong lớp học , -tôi huýt gió lúc đang đi xe đạp , tôi huýt gió ở mọi nơi . -Và tôi huýt gió ở một buổi tiệc đón giáng sinh nữa với gia đình thông gia của tôi . -Và tôi nghĩ , họ có những bài nhạc giáng sinh thật tệ . -Và một khi tôi nghe nhạc mà tôi không thích , tôi cố để làm cho nó hay hơn . -Bài " Con tuần lộc mũi đỏ Rudolph " -- bạn biết bài đó chứ ? -Nhưng nó còn có thể biến tấu như thế này . -Nhưng trong một buổi tiệc giáng sinh kia -- thật ra là một bữa tối -- bữa ấy làm tôi rất khó chịu . -Chị dâu tôi nhắc tôi một vài lần , " Làm ơn đừng huýt gió nữa . " -Nhưng tôi cứ không thể dừng được . -Và tại một thời điểm -- và lúc đó tôi đã uống một ít rượu , tôi phải thừa điều đó -- tại thời điểm đó tôi nói , " Nếu có một cuộc thi , em sẽ tham gia . " -và hai tuần sau Tôi nhận được một tin nhắn : " Em sẽ đi Mỹ đó . " -Đựoc thôi , tôi chuẩn bị được đi Mỹ . -Tôi rất thích , nhưng tại sao ? -Vì vậy tất nhiên tôi gọi chị ấy ngay lập tức . -chị ấy tìm trên google , và chị ấy tìm thấy cuộc thi huýt sáo thế giới ở Mỹ , tất nhiên . -Chị ấy khồng nghĩ tôi sẽ đi . -Và tôi sẽ mất mặt lắm . -Tôi không biết câu đó có đúng ngữ pháp tiếng Anh không . -Nhưng những người nói tiếng Hà Lan ở đây sẽ hiểu ý tôi muốn nói gì . -Tôi đã rất mất mặt -Và cô ấy nghĩ , " Anh ta chắc sẽ khồng bao giờ đi đâu . -Nhưng thật ra tôi đã đi . -Tôi đến Louisburg ở miền bắc Carolina , phí đông nam nước Mỹ. và tôi bước vào thế giới huýt sáo -và tôi cũng tham gia cuộc thi huýt gió thế giới và tôi đã chiến thằng ở đó năm 2004 . -Điều đó -- Điều đó thật tuyệt , tất nhiên . -Và để bảo về danh hiệu của mình -- như judokas do và những vận động viên thể thao -- Tôi nghĩ , năm 2005 hãy quay trở lại đó xem sao , và tôi tiếp tục giành giải quán quân . -Sau đó tôi không thể tham dự cuộc thi trong vòng vài năm . -Và năm 2008 tôi tham gia một lần nữa ở Nhật , thành phố Tokyo , và tôi lại giành giải quán quân . -Và chuyện mới xảy ra ở đây là tôi đứng ở đây , ở Rotterdam , ở một thành phố xinh đẹp , đứng trên một sân khấu lớn , và nói về chuyện huýt gió . -Và trên thực tế tôi kiếm tiền từ huýt gió , tại thời điểm này . -Vì vậy tôi bỏ việc làm của tôi là làm y tá . -Và tôi cố sống giấc mơ của tôi -- nhưng thực ra , đó chưa bao giờ là giấc mơ của tôi , nhưng điều đó nghe thật tuyệt . -Okay , tôi không phải là người huýt gió duy nhất ở đây . -bạn nghĩ , " Hả , ý bạn là gì ? " -Thật ra , bạn sẽ huýt gió cùng tôi -Và sau đó như thường lệ : mọi người nhìn nhau và nghĩ , " Trời đất ơi " -Tại sao ? Tôi có thể đi về được không ? " -Không , bạn không thể -Thật ra huýt gió rất đơn giản . -Bản nhạt mà tôi sẽ huýt theo được gọi là " Fête de la Belle . " -Bản nhạc này dài khoàng 80 phút . -Không không không . Nó chỉ dài bốn phút thôi . -Và tôi muốn luyện tập cho bạn cách huýt gió trước . -Vậy thì tôi sẽ huýt tông của bài nhạc nhé . -Xin lỗi . Tôi quên mất một điều . -Bạn huýt với cái tông giống tôi . -Tôi đã từng nhiều giọng khác nhau , -Đây thật sự là một điều rất hứa hẹn . -Đây thật sự là một điều rất hứa hẹn , -Tôi sẽ hỏi những người ở phía sau cánh gà mở nhạc lên . -Và nếu nhạc bắt đầu , tôi sẽ chỉ chỗ nào để bạn huýt gió theo. và chúng ta sẽ thấy điều gì sẽ xảy ra , -Oh , hah . -Tôi thật sự xin lỗi các bạn kĩ sự ở sau cánh gà . -Tôi đã quen với việc đó rồi . -Tôi sẽ tự bắt đầu -Được rồi , chuẩn bị . -Được rồi . -Rất dễ phải không ? -Phần sô lô chuẩn bị đến . Tôi nghĩ tôi nên làm phần đó . -Max Westerman : Geert Chartrou , nhà vô địch thổi sáo thế giới . -Geert Chatrou : Cám ơn . Cám ơn . -Roberto D 'Angelo + Francesca Fedeli : Bài học cuộc đời từ căn bệnh của con trai tôi . -Roberto D 'Angelo và Francesca Fedeli từng nghĩ con trai Mario của họ khoẻ mạnh -- cho đến khi bé được 10 ngày tuổi , họ phát hiện bé bị đột quỵ sơ sinh . Với Mario không thể điều khiển phần cơ thể bên trái , họ vật lộn với những băn khoăn : Bé có " bình thường " trở lại ? Bé có sống trọn vẹn một đời không ? Một câu chuyện thấm thía về việc cha mẹ đối diện với sự sợ hãi -- và cách họ xoay chuyển chúng . -Francesca Fedeli : Xin chào . -Đây là Mario . Con trai chúng tôi . -Bé mới được 2 tuổi rưỡi , tôi đã có khoảng thời gian mang bầu thật khó khăn vì phải nằm trên giường gần 8 tháng . -Nhưng cuối cùng thì mọi việc dường như đã ổn . -Nên bé sinh ra được đủ cân nặng . -Bé có chỉ số Apgar tốt . -Nên chúng tôi khá an tâm . -Nhưng cuối cùng , 10 ngày sau khi sinh , chúng tôi phát hiện bé bị đột quỵ . -Như bạn biết đấy , đột quỵ là một sự tổn thương não . -Đột quỵ sơ sinh là một chuyện có thể xảy ra trong 9 tháng mang thai hoặc bất ngờ ngay sau khi sinh , trong trường hợp của bé , như bạn thấy , phần não phải của bé đã không còn . -Hậu quả của cú đột quỵ đối với cơ thể của Mario có thể tệ đến mức Mario sẽ không còn có thể sử dụng được phần cơ thể bên trái nữa . -Hãy tưởng tượng , nếu bạn có một máy tính và một máy in và bạn muốn gửi , muốn in ra một tài liệu , nhưng máy in không có những ổ đĩa phù hợp , Mario cũng vậy . -Giống như , bé muốn di chuyển phần cơ thể bên trái nhưng không thể chuyển giao tín hiệu để chuyển động tay và chân trái . -Vậy là cuộc sống đã phải thay đổi . -Chúng tôi phải thay đổi kế hoạch của mình . -Chúng tôi phải thay đổi những ảnh hưởng của việc sinh nở này với đời mình . -Như bạn tưởng tượng , không may là chúng tôi chưa sẵn sàng . -Không ai dạy chúng tôi xử lý những khuyết tật như vậy thế nào , và ngày càng có nhiều băn khoăn bắt đầu chiếm lấy tâm trí chúng tôi . -Đó thực sự là quãng thời gian khó khăn . -Những băn khoăn , những điều cơ bản như , bạn biết đấy , tại sao chuyện này xảy đến với chúng tôi ? -Vấn đề ở chỗ nào ? -Một số băn khoăn nặng nề hơn , như là cuộc sống của Mario sẽ bị ảnh hưởng thế nào ? -Ý tôi là , rồi bé sẽ có thể làm việc không ? -Bé sẽ có thể bình thường trở lại ? -Và , như bạn biết , là cha mẹ , nhất là lần đầu tiên , tại sao bé sẽ không trở nên tốt hơn so với chúng tôi ? -Và điều này , thật ra là , thực sự rất khó nói ra , nhưng vài tháng sau , chúng tôi nhận ra chúng tôi thực sự cảm thấy như mình thất bại . -Ý tôi là thành quả thực tế duy nhất của đời mình , cuối cùng , lại là một thất bại . -Và bạn biết đó , nó không phải là thất bại với chính bản thân chúng tôi mà là thất bại sẽ ảnh hưởng đến suốt đời Mario . -Thành thật mà nói , chúng tôi thất vọng . -Ý tôi là thực sự thất vọng , nhưng cuối cùng , chúng tôi nhìn lại bé , và cùng nói , chúng ta phải hành động . -Ngay lập tức , như Francesca đã nói , chúng tôi thay đổi đời mình . -Chúng tôi bắt đầu liệu pháp phục hồi chức năng và vật lí trị liệu. và một trong những hướng mà chúng tôi đang theo đuổi trong vật lí trị liệu là hướng dẫn neuron đối chiếu . -Về cơ bản , chúng tôi làm việc này cùng Mario trong nhiều tháng . -Bạn có một đồ vật , chúng tôi chỉ cách cho bé làm thế nào để nắm lấy các đồ vật đó . -Vâng , lý thuyết neuron đối chiếu nói một cách đơn giản rằng trong não bạn , chính xác như bây giờ , khi bạn thấy tôi làm thế này , bạn kích hoạt đúng những neuron như tôi giống như chính bạn đang làm vậy . -Có vẻ như đây là một sự đột phá trong vật lí trị liệu . -Nhưng một hôm , chúng tôi phát hiện ra Mario không nhìn vào tay chúng tôi . -Bé nhìn vào chúng tôi . -Chúng tôi là tấm gương của bé . -Và vấn đề , như có thể bạn thấy , rằng chúng tôi thất vọng , chúng tôi suy sụp , chúng tôi đã coi bé như một vấn đề chứ không phải là một bé trai , không từ một nhận thức tích cực . -Ngày hôm đó thực sự thay đổi nhận thức của chúng tôi . -Chúng tôi nhận ra mình phải trở thành một tấm gương tốt hơn cho Mario . -Chúng tôi bắt đầu lại từ nghị lực , đồng thời , bắt đầu lại từ khả năng của bé . -Chúng tôi không còn coi bé là một vấn đề nữa , và chúng tôi bắt đầu coi bé như một cơ hội để trở nên tốt hơn . -Và thực sự , điều này đã thay đổi , từ phía chúng tôi , chúng tôi nói , " Chúng ta có khả năng gì để trao cho Mario ? " -Và chúng tôi bắt đầu từ mong muốn của mình . -Ý tôi là , cuối cùng , vợ tôi và tôi cũng khá khác nhau , nhưng chúng tôi có nhiều điểm chung . -Chúng tôi thích du lịch , yêu âm nhạc , thích ở những nơi thế này , và bắt đầu đưa Mario đi cùng chỉ để cho cháu thấy những gì tốt nhất chúng tôi có thể chỉ cho cháu . -Video này được quay từ tuần trước . -Tôi không nói rằng -- -- Tôi không nói đó là phép màu . Đó không phải là thông điệp , vì chúng tôi mới chỉ bắt đầu chặng đường . -Nhưng chúng tôi muốn chia sẻ nhận thức cốt yếu , nhận thức cốt yếu mà Mario đã đưa chúng tôi tới , rằng hãy coi những gì bạn có một như món quà chứ không phải là những gì bạn đã bỏ lỡ , và coi những gì bạn đã bỏ lỡ chỉ như một cơ hội . -Và đây là thông điệp mà chúng tôi muốn chia sẻ với các bạn . -Đây là lí do tại sao chúng tôi tới đây . -Mario ! -Và đây là lí do -- -- Và đây là lí do chúng tôi quyết định chia sẻ tấm gương tốt nhất trên đời với bé . -Cảm ơn các bạn rất nhiều , tất cả các bạn . -Xin cảm ơn . Cảm ơn . Tạm biệt . -Cảm ơn . -Mark Shaw : Bài biểu diễn rất khô -Mark Shaw giới thiệu chất Cực Khô , một dạng chất lỏng phủ bề ngoài có thể chống thấm nước và những chất có chứa nước . Ở mức độ phân từ nano , chất này bao phủ bề mặt vật liệu bởi lớp không khí bảo vệ , vì vậy nước không thấm được . Bạn hãy xem một màn biểu diễn tuyệt vời trong vòng hai phút nhé . -Hôm nay tôi đến đây để chỉ cho các bạn Những thứ bạn không thể thấy được nhưng rất thú vị khi nhìn vào đó -Các bạn sắp sửa thử một loại kĩ thuật mới và rất thú vị , làm cho chúng ta suy nghĩ lại chúng ta chống thấm nước như thế nào -Tôi có một khối đá xỉ ở đây một nửa đã được phủ lớp xịt vi phân tử - kĩ thuật nano có thể áp dụng cho hầu hết các loại vật liệu . -Đó gọi là chất Cực Khô và khi bạn bôi vào vật liệu nó sẽ hình thành lớp màng chống thấm nước -Đây là khối đá xỉ , trơn và bạn thấy nó rỗng , có thể hút nước . -Đây thì không . -Rỗng , không rỗng . -Vậy tính chống thấm nước là như thế nào ? -Đô chống thấm là khả năng đo một giọt nước trên bề mặt . -Giọt nước càng tròn , độ chống thấm càng cao , và nếu như rất tròn , nó chống thấm cực tốt . -Một xe vừa bôi sáp , những phân tử nước sụt xuống gần ̣ 90 độ . -Một lớp kinh chắn gió cho ta khoảng 110 độ . -Chúng ta đang nhìn thấy đây là 160 - 175 độ , và từ 150 độ trở đi là chống thấm cực tốt rồi . -Một phần của buổi thuyết trình , tôi có một đôi găng tay và chỉ phủ một chiếc với lớp chống thấm vi phân tử hãy xem xem chiếc găng nào nhé , tôi sẽ gợi ý -Bạn đoán ra chiếc nào khô rồi chứ ? -Khi chúng ta có kĩ thuật vi phân tử và khoa học vi phân tử chúng ta có thể nhìn thấy nguyên tử và phân tử và có thể điều khiển chúng để đem lại nhiều lợi ích -Chúng ta nói đến " rất nhỏ " ở đây -Khoa học vi phân tử có kích thước nanomét một nano mét bằng một phần tỉ mét , để đo chúng , nếu bạn có một phân tử nano , kích thước một nano mét , nếu đặt 50,000 hạt với nhau , sẽ bằng bề dày của sợi tóc . -Vậy thì rất nhỏ , nhưng rất hữu dụng . -Không chỉ có nước -còn rất nhiều chất có nước như bê tông , sơn có chứa nước , bùn , và một số loại dầu tinh chế nữa . -Bạn có thể thấy sự khác biệt . -Phần kế tiếp , chúng ta có tấm kính ô vuông này , và đã được phủ lớp chống thấm ở rìa bao phủ lớp chống thấm vi phân tử , và ta sẽ nhỏ thứ nước nhuộm xanh này vào chính giữa , bạn sẽ thấy , nó sẽ tràn ra ngoài tấm kính như bạn thường thấy , ngoại trừ phần đã được phủ và tôi không thể làm cho nó tràn ra . -Đó là tính sợ nước . -Vậy thì chuyện gì đã xảy ra vậy ? -Bề mặt của lớp phủ chứa những phân tử nano hình thành lớp bề mặt rất thô . -Bạn có thể nghĩ là nó trơn , nhưng không phải vậy . -Và có hàng tỉ khe hở giữa chúng , những kẽ hở này , và những phân tử nano chiếm lấy những phân tử không khí và bao phủ lớp ngoài bởi không khí . -Đó hình thành lớp ô bảo vệ vậy là nước tác động vào lớp không khí bùn , bê tông , đều trượt đi hết . -Nếu tôi cho tấm ván này vào nước , bạn thấy lớp bạc óng ánh xung quanh nó , và lớp bạc này chính là lớp không khí bảo vệ để nước khỏi chạm vào tấm ván , và nó hoàn toàn khô . -Vậy thì ứng dụng ở đây là gì ? -Có thể các bạn đang suy nghĩ trong đầu -Mọi người có thể rất phấn khởi , cho rằng , " Ồ , tôi có thể sử dụng vào việc này , việc nọ . " -Những ứng dụng thường thấy là những chất chống ẩm . -Ngày nay chúng ta đã thấy -những chất chống đóng băng , vì bạn không có nước , bạn không có băng . -Đó có thể là chất chống rỉ sét . -Không có nước , không có rỉ sét . -Có thể là chống vi khuẩn . -Không có nước , vi khuẩn không kí sinh được . -Và tất cả những chất tự rửa -Thử tưởng tượng những ứng dụng này có thể cải tiến lĩnh vực bạn đang làm . -Sau đây là bài biểu diễn cuối cùng của tôi , nhưng trước đó , tôi muốn cảm ơn tất cả các bạn , và nghĩ ít thôi nhé . -Sẽ được thôi . Từ từ . -Bạn biết chúng tôi cắt biển hiệu của chương trình TED chứ ? -[ Hai phút sau ... ] Ông ấy có rất nhiều nghiên cứu y học . -Được rồi ! -̣ -Dan Ariely bàn về đoạn mã đạo đức bị lỗi của con người -Nhà kinh tế học hành vi Dan Ariely nghiên cứu các lỗi trong đoạn mã phẩm chất đạo đức của chúng ta : lý do tiềm ẩn khiến chúng ta nghĩ sẽ chẳng sao nếu gian lận hoặc trộm đồ . Các nghiên cứu khéo léo giúp làm rõ ý tưởng của ông về việc chúng ta cư xử vô lý - và có thể bị ảnh hưởng theo những cách chúng ta không hiểu hết . -Hôm nay , tôi muốn nói 1 chút về tính phi lý có thể lường trước được -Niềm đam mê của tôi về lĩnh vực này bắt đầu cách đây nhiều năm trong bệnh viện . -Khi ấy tôi bị bỏng nặng . -Nếu chẳng may bạn phải dành nhiều thời gian ở bệnh viện , bạn sẽ bắt gặp nhiều dạng phi lý -Một điều đặc biệt gây khó khăn cho tôi tại khoa điều trị bỏng là quá trình các y tá tháo băng cho tôi . -Bây giờ , bạn phải tháo băng y tế tại 1 số vị trí , bạn phải cẩn thận xem xét đâu là cách làm đúng -Cách 1 : bóc nó ra nhanh - thời gian ngắn nhưng phải khá mạnh tay hoặc cách 2 : bạn tháo băng từ từ-- mất khá nhiều thời gian- nhưng từng giây qua đi bớt đau đớn hơn-- Vậy cách nào là đúng ? -Các y tá trong khoa tôi nằm cho rằng phương pháp đúng nhất là cách 1 , họ giữ 1 đầu và bắt đầu bóc và giữ 1 đầu rồi bóc . -Vì tôi bị bỏng 70 % cơ thể nên mất khoảng 1 tiếng tháo băng . -Như bạn có thể tưởng tượng tôi căm ghét cái khoảnh khắc bóc toạc với 1 sức mạnh kinh hồn . -Và tôi sẽ cố gắng lý sự với họ " Tại sao chúng ta không thử cách khác ? " -" Tại sao chúng ta không làm lâu hơn 1 chút 2 tiếng thay vì 1 tiếng , và nhẹ tay hơn ? " -Và các y tá nói với tôi 2 điều . -Họ nói rằng mẫu bệnh nhân đúng mực là những người tin tưởng vào các y tá luôn thao tác đúng để giảm đau tối đa và họ cũng nói rằng bệnh nhân không nên gợi ý hay can thiệp , hoặc ... -Đây không phải bằng chữ Hebrew -Nó bằng mọi thứ ngôn ngữ tôi từng biết -Và , bạn biết đấy , không có nhiều nhiều thứ tôi có thể làm và họ tiếp tục làm công việc của mình . -Và khoảng 3 năm sau , khi tôi ra viện , tôi đã bắt đầu học đại học -Và 1 trong số các bài học thú vị nhất tôi đã học là phương pháp thử nghiệm nghĩa là nếu bạn nghi vấn điều gì , bạn có thể tạo 1 bản mô phỏng nghi vấn một cách trừu tượng , bạn có thể cố gắng kiểm tra nghi vấn , có thể học được chút gì về thế giới . -Đó là những gì tôi đã làm . -Tôi vẫn rất quan tâm đến câu hỏi làm cách nào để tháo băng y tế cho bệnh nhân bỏng . -Ban đầu tôi không có nhiều tiền , vì thế tôi đã đến cửa hàng kim khí và mua 1 cái bàn kẹp thợ mộc . -Sau đó tôi mang mọi người tới phòng thí nhiệm , đặt ngón tay họ vào đó , và tôi kẹp họ 1 chút . -Và tôi kẹp trong 1 khoảng thời gian dài và ngắn , cơn đau lúc tăng lúc giảm , có lúc nghỉ ngơi và có lúc không- tất cả các mức độ đau đớn . -Sau khi thôi không làm đau mọi người nữa , tôi sẽ hỏi họ Bạn có đau không ? Đau như thế nào ? -Hoặc nếu được chọn giữa 2 kiểu đau cuối , bạn sẽ chọn cái nào ? -Tôi tiếp tục làm thí nghiệm này 1 thời gian -Và sau đó , giống các đề tài nghiên cứu hay khác , tôi nhận thêm nguồn tài trợ .