## How to make a toy English-German translator with multi-head attention heat maps: the overall architecture of Transformer

If you have been patient enough to read the former articles of this article series Instructions on Transformer for people outside NLP field, but with examples of NLP, you should have already learned a great deal of Transformer model, and I hope you gained a solid foundation of learning theoretical sides on this algorithm.

This article is going to focus more on practical implementation of a transformer model. We use codes in the Tensorflow official tutorial. They are maintained well by Google, and I think it is the best practice to use widely known codes.

The figure below shows what I have explained in the articles so far. Depending on your level of understanding, you can go back to my former articles. If you are familiar with NLP with deep learning, you can start with the third article.

### 1 The datasets

I think this article series appears to be on NLP, and I do believe that learning Transformer through NLP examples is very effective. But I cannot delve into effective techniques of processing corpus in each language. Thus we are going to use a library named BPEmb. This library enables you to encode any sentences in various languages into lists of integers. And conversely you can decode lists of integers to the language. Thanks to this library, we do not have to do simplification of alphabets, such as getting rid of Umlaut.

*Actually, I am studying in computer vision field, so my codes would look elementary to those in NLP fields.

The official Tensorflow tutorial makes a Portuguese-English translator, but in article we are going to make an English-German translator. Basically, only the codes below are my original. As I said, this is not an article on NLP, so all you have to know is that at every iteration you get a batch of (64, 41) sized tensor as the source sentences, and a batch of (64, 42) tensor as corresponding target sentences. 41, 42 are respectively the maximum lengths of the input or target sentences, and when input sentences are shorter than them, the rest positions are zero padded, as you can see in the codes below.

*If you just replace datasets and modules for encoding, you can make translators of other pairs of languages.

We are going to train a seq2seq-like Transformer model of converting those list of integers, thus a mapping from a vector to another vector. But each word, or integer is encoded as an embedding vector, so virtually the Transformer model is going to learn a mapping from sequence data to another sequence data. Let’s formulate this into a bit more mathematics-like way: when we get a pair of sequence data and , where , respectively from English and German corpus, then we learn a mapping .

*In this implementation the vocabulary sizes are both . Thus

### 2 The whole architecture

This article series has covered most of components of Transformer model, but you might not understand how seq2seq-like models can be constructed with them. It is very effective to understand how transformer is constructed by actually reading or writing codes, and in this article we are finally going to construct the whole architecture of a Transforme translator, following the Tensorflow official tutorial. At the end of this article, you would be able to make a toy English-German translator.

The implementation is mainly composed of 4 classes, EncoderLayer(), Encoder(), DecoderLayer(), and Decoder() class. The inclusion relations of the classes are displayed in the figure below.

To be more exact in a seq2seq-like model with Transformer, the encoder and the decoder are connected like in the figure below. The encoder part keeps converting input sentences in the original language through layers. The decoder part also keeps converting the inputs in the target languages, also through layers, but it receives the output of the final layer of the Encoder at every layer.

You can see how the Encoder() class and the Decoder() class are combined in Transformer in the codes below. If you have used Tensorflow or Pytorch to some extent, the codes below should not be that hard to read.

### 3 The encoder

*From now on “sentences” do not mean only the input tokens in natural language, but also the reweighted and concatenated “values,” which I repeatedly explained in explained in the former articles. By the end of this section, you will see that Transformer repeatedly converts sentences layer by layer, remaining the shape of the original sentence.

I have explained multi-head attention mechanism in the third article, precisely, and I explained positional encoding and masked multi-head attention in the last article. Thus if you have read them and have ever written some codes in Tensorflow or Pytorch, I think the codes of Transformer in the official Tensorflow tutorial is not so hard to read. What is more, you do not use CNNs or RNNs in this implementation. Basically all you need is linear transformations. First of all let’s see how the EncoderLayer() and the Encoder() classes are implemented in the codes below.

You might be confused what “Feed Forward” means in  this article or the original paper on Transformer. The original paper says this layer is calculated as . In short you stack two fully connected layers and activate it with a ReLU function. Let’s see how point_wise_feed_forward_network() function works in the implementation with some simple codes. As you can see from the number of parameters in each layer of the position wise feed forward neural network, the network does not depend on the length of the sentences.

From the number of parameters of the position-wise feed forward neural networks, you can see that you share the same parameters over all the positions of the sentences. That means in the figure above, you use the same densely connected layers at all the positions, in single layer. But you also have to keep it in mind that parameters for position-wise feed-forward networks change from layer to layer. That is also true of “Layer” parts in Transformer model, including the output part of the decoder: there are no learnable parameters which cover over different positions of tokens. These facts lead to one very important feature of Transformer: the number of parameters does not depend on the length of input or target sentences. You can offset the influences of the length of sentences with multi-head attention mechanisms. Also in the decoder part, you can keep the shape of sentences, or reweighted values, layer by layer, which is expected to enhance calculation efficiency of Transformer models.

### 4, The decoder

The structures of DecoderLayer() and the Decoder() classes are quite similar to those of EncoderLayer() and the Encoder() classes, so if you understand the last section, you would not find it hard to understand the codes below. What you have to care additionally in this section is inter-language multi-head attention mechanism. In the third article I was repeatedly explaining multi-head self attention mechanism, taking the input sentence “Anthony Hopkins admired Michael Bay as a great director.” as an example. However, as I explained in the second article, usually in attention mechanism, you compare sentences with the same meaning in two languages. Thus the decoder part of Transformer model has not only self-attention multi-head attention mechanism of the target sentence, but also an inter-language multi-head attention mechanism. That means, In case of translating from English to German, you compare the sentence “Anthony Hopkins hat Michael Bay als einen großartigen Regisseur bewundert.” with the sentence itself in masked multi-head attention mechanism (, just as I repeatedly explained in the third article). On the other hand, you compare “Anthony Hopkins hat Michael Bay als einen großartigen Regisseur bewundert.” with “Anthony Hopkins admired Michael Bay as a great director.” in the inter-language multi-head attention mechanism (, just as you can see in the figure above).

*The “inter-language multi-head attention mechanism” is my original way to call it.

I briefly mentioned how you calculate the inter-language multi-head attention mechanism in the end of the third article, with some simple codes, but let’s see that again, with more straightforward figures. If you understand my explanation on multi-head attention mechanism in the third article, the inter-language multi-head attention mechanism is nothing difficult to understand. In the multi-head attention mechanism in encoder layers, “queries”, “keys”, and “values” come from the same sentence in English, but in case of inter-language one, only “keys” and “values” come from the original sentence, and “queries” come from the target sentence. You compare “queries” in German with the “keys” in the original sentence in English, and you re-weight the sentence in English. You use the re-weighted English sentence in the decoder part, and you do not need look-ahead mask in this inter-language multi-head attention mechanism.

Just as well as multi-head self-attention, you can calculate inter-language multi-head attention mechanism as follows: . In the example above, the resulting multi-head attention map is a matrix like in the figure below.

Once you keep the points above in you mind, the implementation of the decoder part should not be that hard.

### 5 Masking tokens in practice

I explained masked-multi-head attention mechanism in the last article, and the ideas itself is not so difficult. However in practice this is implemented in a little tricky way. You might have realized that the size of input matrices is fixed so that it fits the longest sentence. That means, when the maximum length of the input sentences is 41, even if the sentences in a batch have less than 41 tokens, you sample (64, 41) sized tensor as a batch every time (The 64 is a batch size). Let “Anthony Hopkins admired Michael Bay as a great director.”, which has 9 tokens in total, be an input. We have been considering calculating (9, 9) sized attention maps or (10, 9) sized attention maps, but in practice you use (41, 41) or (42, 41) sized ones. When it comes to calculating self attentions in the encoder part, you zero pad self attention maps with encoder padding masks, like in the figure below. The black dots denote the zero valued elements.

As you can see in the codes below, encode padding masks are quite simple. You just multiply the padding masks with -1e9 and add them to attention maps and apply a softmax function. Thereby you can zero-pad the columns in the positions/columns where you added -1e9 to.

I explained look ahead mask in the last article, and in practice you combine normal padding masks and look ahead masks like in the figure below. You can see that you can compare each token with only its previous tokens. For example you can compare “als” only with “Anthony”, “Hopkins”, “hat”, “Michael”, “Bay”, “als”, not with “einen”, “großartigen”, “Regisseur” or “bewundert.”

Decoder padding masks are almost the same as encoder one. You have to keep it in mind that you zero pad positions which surpassed the length of the source input sentence.

### 6 Decoding process

In the last section we have seen that we can zero-pad columns, but still the rows are redundant. However I guess that is not a big problem because you decode the final output in the direction of the rows of attention maps. Once you decode <end> token, you stop decoding. The redundant rows would not affect the decoding anymore.

This decoding process is similar to that of seq2seq models with RNNs, and that is why you need to hide future tokens in the self-multi-head attention mechanism in the decoder. You share the same densely connected layers followed by a softmax function, at all the time steps of decoding. Transformer has to learn how to decode only based on the words which have appeared so far.

According to the original paper, “We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position can depend only on the known outputs at positions less than .” After these explanations, I think you understand the part more clearly.

The codes blow is for the decoding part. You can see that you first start decoding an output sentence with a sentence composed of only <start>, and you decide which word to decoded, step by step.

*It easy to imagine that this decoding procedure is not the best. In reality you have to consider some possibilities of decoding, and you can do that with beam search decoding.

After training this English-German translator for 30 epochs you can translate relatively simple English sentences into German. I displayed some results below, with heat maps of multi-head attention. Each colored attention maps corresponds to each head of multi-head attention. The examples below are all from the fourth (last) layer, but you can visualize maps in any layers. When it comes to look ahead attention, naturally only the lower triangular part of the maps is activated.

This article series has not covered some important topics machine translation, for example how to calculate translation errors. Actually there are many other fascinating topics related to machine translation. For example beam search decoding, which consider some decoding possibilities, or other topics like how to handle proper nouns such as “Anthony” or “Hopkins.” But this article series is not on NLP. I hope you could effectively learn the architecture of Transformer model with examples of languages so far. And also I have not explained some details of training the network, but I will not cover that because I think that depends on tasks. The next article is going to be the last one of this series, and I hope you can see how Transformer is applied in computer vision fields, in a more “linguistic” manner.

But anyway we have finally made it. In this article series we have seen that one of the earliest computers was invented to break Enigma. And today we can quickly make a more or less accurate translator on our desk. With Transformer models, you can even translate deadly funny jokes into German.

*You can train a translator with this code.

*After training a translator, you can translate English sentences into German with this code.

[References]

[1] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, “Attention Is All You Need” (2017)

[2] “Transformer model for language understanding,” Tensorflow Core
https://www.tensorflow.org/overview

[3] Jay Alammar, “The Illustrated Transformer,”
http://jalammar.github.io/illustrated-transformer/

[4] “Stanford CS224N: NLP with Deep Learning | Winter 2019 | Lecture 14 – Transformers and Self-Attention,” stanfordonline, (2019)

[5]Tsuboi Yuuta, Unno Yuuya, Suzuki Jun, “Machine Learning Professional Series: Natural Language Processing with Deep Learning,” (2017), pp. 91-94

* I make study materials on machine learning, sponsored by DATANOMIQ. I do my best to make my content as straightforward but as precise as possible. I include all of my reference sources. If you notice any mistakes in my materials, including grammatical errors, please let me know (email: yasuto.tamura@datanomiq.de). And if you have any advice for making my materials more understandable to learners, I would appreciate hearing it.

## Positional encoding, residual connections, padding masks: covering the rest of Transformer components

This is the fourth article of my article series named “Instructions on Transformer for people outside NLP field, but with examples of NLP.”

### 1 Wrapping points up so far

This article series has already covered a great deal of the Transformer mechanism. Whether you have read my former articles or not, I bet you are more or less lost in the course of learning Transformer model. The left side of the figure below is from the original paper on Transformer model, and my previous articles explained the parts in each colored frame. In the first article, I  mainly explained how language is encoded in deep learning task and how that is evaluated.

This is more of a matter of inputs and the outputs of deep learning networks, which are in blue dotted frames in the figure. They are not so dependent on types of deep learning NLP tasks. In the second article, I explained seq2seq models, which are encoder-decoder models used in machine translation. Seq2seq models can can be simplified like the figure in the orange frame. In the article I mainly explained seq2seq models with RNNs, but the purpose of this article series is ultimately replace them with Transformer models. In the last article, I finally wrote about some actual components of Transformer models: multi-head attention mechanism. I think this mechanism is the core of Transformed models, and I did my best to explain it with a whole single article, with a lot of visualizations. However, there are still many elements I have not explained.

First, you need to do positional encoding to the word embedding so that Transformer models can learn the relations of the positions of input tokens. At least I was too stupid to understand what this is only with the original paper on Transformer. I am going to explain this algorithm in illustrative ways, which I needed to self-teach it. The second point is residual connections.

The last article has already explained multi-head attention, as precisely as I could do, but I still have to say I covered only two multi-head attention parts in a layer of Transformer model, which are in pink frames. During training, you have to mask some tokens at the decoder part so that some of tokens are invisible, and masked multi-head attention enables that.

You might be tired of the words “queries,” “keys,” and “values,” if you read the last article. But in fact that was not enough. When you think about applying Transformer in other tasks, such as object detection or image generation, you need to reconsider what the structure of data and how “queries,” “keys,” and “values,” correspond to each elements of the data, and probably one of my upcoming articles would cover this topic.

### 2 Why Transformer?

One powerful strength of Transformer model is its parallelization. As you saw in the last article, Trasformer models enable calculating relations of tokens to all other tokens, on different standards, independently in each head. And each head requires very simple linear transformations. In case of RNN encoders, if an input has tokens, basically you have to wait for time steps to finish encoding the input sentence. Also, at the time step the RNN cell retains the information at the time step only via recurrent connections. In this way you cannot attend to tokens in the earlier time steps, and this is obviously far from how we compare tokens in a sentence. You can bring information backward by bidirectional connection s in RNN models, but that all the more deteriorate parallelization of the model. And possessing information via recurrent connections, like a telephone game, potentially has risks of vanishing gradient problems. Gated RNN, such as LSTM or GRU mitigate the problems by a lot of nonlinear functions, but that adds to computational costs. If you understand multi-head attention mechanism, I think you can see that Transformer solves those problems.

I guess this is closer to when you speak a foreign language which you are fluent in. You wan to say something in a foreign language, and you put the original sentence in your mother tongue in the “encoder” in your brain. And you decode it, word by word, in the foreign language. You do not have to wait for the word at the end in your language, or rather you have to consider the relations of of a chunk of words to another chunk of words, in forward and backward ways. This is crucial especially when Japanese people speak English. You have to make the conclusion clear in English usually with the second word, but the conclusion is usually at the end of the sentence in Japanese.

### 3 Positional encoding

I explained disadvantages of RNN in the last section, but RNN has been a standard algorithm of neural machine translation. As I mentioned in the fourth section of the first article of my series on RNN, other neural nets like fully connected layers or convolutional neural networks cannot handle sequence data well. I would say RNN could be one of the only algorithms to handle sequence data, including natural language data, in more of classical methods of time series data processing.

*As I explained in this article, the original idea of RNN was first proposed in 1997, and I would say the way it factorizes time series data is very classical, and you would see similar procedures in many other algorithms. I think Transformer is a successful breakthrough which gave up the idea of processing sequence data time step by time step.

You might have noticed that multi-head attention mechanism does not explicitly uses the the information of the orders or position of input data, as it basically calculates only the products of matrices. In the case where the input is “Anthony Hopkins admired Michael Bay as a great director.”, multi head attention mechanism does not uses the information that “Hopkins” is the second token, or the information that the token two time steps later is “Michael.” Transformer tackles this problem with an almost magical algorithm named positional encoding.

In order to learn positional encoding, you should first think about what kind of encoding is ideal. According to this blog post, ideal encoding of positions of tokens have the following features.

• Positional encoding of one token deterministically represents the position of the token.
• The actual values of positional encoding should not be too big compared to the values of elements of embedding vectors.
• Positional encodings of different tokens should successfully express their relative positions.

The most straightforward way to give the information of position is implementing the index of times steps , but if you naively give the term to the data, the term could get too big compared to the values of data ,for example when the sequence data is 100 time steps long. The next straightforward idea is compressing the idea of time steps to for example the range . With this approach, however, the resolution of encodings can vary depending on the length of the input sequence data. Thus these naive approaches do not meet the requirements above, and I guess even conventional RNN-based models were not so successful in these points.

*I guess that is why attention mechanism of RNN seq2seq models, which I explained in the second article, was successful. You can constantly calculate the relative positions of decoder tokens compared to the encoder tokens.

Positional encoding, to me almost magically, meets the points I have mentioned. However the explanation of positional encoding in the original paper of Transformer is unkindly brief. It says you can encode positions of tokens with the following vector , , where . is the dimension of word embedding. The heat map below is the most typical type of visualization of positional encoding you would see everywhere, and in this case , and is discrete number which varies from to , thus the heat map blow is equal to a matrix, whose elements are from to . Each row of the graph corresponds to one token, and you can see that lower dimensional part is constantly changing like waves. Also it is quite easy to encode an input with this positional encoding: assume that you have a matrix of an input sentence composed of 50 tokens, each of which is a 256 dimensional vector, then all you have to do is just adding the heat map below to the matrix.

Concretely writing down, the encoding of the 256-dim token at   is .

You should see this encoding more as pairs of circles rather than dimensional vectors. When you fix the , the index of the depth of each encoding, you can extract a 2 dimensional vector . If you constantly change the value , the vector rotates clockwise on the unit circle in the figure below.

Also, the deeper the dimension of the embedding is, I mean the bigger the index is, the smaller the frequency of rotation is. I think the video below is a more intuitive way to see how each token is encoded with positional encoding. You can see that the bigger is, that is the more tokens an input has, the deeper part positional encoding starts to rotate on the circles.

Very importantly, the original paper of Transformer says, “We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset , can be represented as a linear function of .” For each circle at any depth, I mean for any , the following simple equation holds:

The matrix is a simple rotation matrix, so if is fixed the rotation only depends on , how many positions to move forward or backward. Then we get a very important fact: as the changes ( is a discrete number), each point rotates in proportion to the offset of “pos,” with different frequencies depending on the depth of the circles. The deeper the circle is, the smaller the frequency is. That means, this type of positional encoding encourages Transformer models to learn definite and relative positions of tokens with rotations of those circles, and the values of each element of the rotation matrices are from to , so they do not get bigger no matter how many tokens inputs have.

For example when an input is “Anthony Hopkins admired Michael Bay as a great director.”, a shift from the token “Hopkins” to “Bay” is a rotation matrix  , where . Also the shift from “Bay” to “great” has the same rotation.

*Positional encoding reminded me of Enigma, a notorious cipher machine used by Nazi Germany. It maps alphabets to different alphabets with different rotating gear connected by cables. With constantly changing gears and keys, it changed countless patterns of alphabetical mappings, every day, which is impossible for humans to solve. One of the first form of computers was invented to break Enigma.

*As far as I could understand from “Imitation Game (2014).”

*But I would say Enigma only relied on discrete deterministic algebraic mapping of alphabets. The rotations of positional encoding is not that tricky as Enigma, but it can encode both definite and deterministic positions of much more variety of tokens. Or rather I would say AI algorithms developed enough to learn such encodings with subtle numerical changes, and I am sure development of NLP increased the possibility of breaking the Turing test in the future.

### 5 Residual connections

If you naively stack neural networks with simple implementation, that would suffer from vanishing gradient problems during training. Back propagation is basically multiplying many gradients, so

One way to mitigate vanishing gradient problems is quite easy: you have only to make a bypass of propagation. You would find a lot of good explanations on residual connections, so I am not going to explain how this is effective for vanishing gradient problems in this article.

In Transformer models you add positional encodings to the input only in the first layer, but I assume that the encodings remain through the layers by these bypass routes, and that might be one of reasons why Transformer models can retain information of positions of tokens.

Even though Transformer, unlike RNN, can attend to the whole input sentence at once, the decoding process of Transformer-based translator is close to RNN-based one, and you are going to see that more clearly in the codes in the next article. As I explained in the second article, RNN decoders decode each token only based on the tokens the have generated so far. Transformer decoder also predicts the output sequences autoregressively one token at a time step, just as RNN decoders. I think it easy to understand this process because RNN decoder generates tokens just as you connect RNN cells one after another, like connecting rings to a chain. In this way it is easy to make sure that generating of one token in only affected by the former tokens. On the other hand, during training Transformer decoders, you input the whole sentence at once. That means Transformer decoders can see the whole sentence during training. That is as if a student preparing for a French translation test could look at the whole answer French sentences. It is easy to imagine that you cannot prepare for the French test effectively if you study this way. Transformer decoders also have to learn to decode only based on the tokens they have generated so far.

In order to properly train a Transformer-based translator to learn such decoding, you have to hide the upcoming tokens in target sentences during training. During calculating multi-head attentions in each Transformer layer, if you keep ignoring the weights from up coming tokens like in the figure below, it is likely that Transformer models learn to decode only based on the tokens generated so far. This is called masked multi-head attention.

*I am going to take an input “Anthonly Hopkins admire Michael Bay as a great director.” as an example of calculating masked multi-head attention mechanism, but this is supposed to be in the target laguage. So when you train an translator from English to German, in practice you have to calculate masked multi-head atetntion of “Anthony Hopkins hat Michael Bay als einen großartigen Regisseur bewundert.”

As you can see from the whole architecture of Transformer, you only need to consider masked multi-head attentions of of self-attentions of the input sentences at the decoder side. In order to concretely calculate masked multi-head attentions, you need a technique named look ahead masking. This is also quite simple. Just as well as the last article, let’s take an example of calculating self attentions of an input “Anthony Hopkins admired Michael Bay as a great director.” Also in this case you just calculate multi-head attention as usual, but when you get the histograms below, you apply look ahead masking to each histogram and delete the weights from the future tokens. In the figure below the black dots denote zero, and the sum of each row of the resulting attention map is also one. In other words, you get a lower triangular matrix, the sum of whose each row is 1.

Also just as I explained in the last article, you reweight vlaues with the triangular attention map. The figure below is calculating a transposed masked multi-head attention because I think it is a more straightforward way to see how vectors are reweighted in multi-head attention mechanism.

When you closely look at how each column of the transposed multi-head attention is reweighted, you can clearly see that the token is reweighted only based on the tokens generated so far.

*If you are still not sure why you need such masking in multi-head attention of target sentences, you should proceed to the next article for now. Once you check the decoding processes of Transformer-based translators, you would see why you need masked multi-head attention mechanism on the target sentence during training.

If you have read my articles, at least this one and the last one, I think you have gained more or less clear insights into how each component of Transfomer model works. You might have realized that each components require simple calculations. Combined with the fact that multi-head attention mechanism is highly parallelizable, Transformer is easier to train, compared to RNN.

In this article, we are going to see how masking of multi-head attention is implemented and how the whole Transformer structure is constructed. By the end of the next article, you would be able to create a toy English-German translator with more or less clear understanding on its architecture.

### Appendix

You can visualize positional encoding the way I explained with simple Python codes below. Please just copy and paste them, importing necessary libraries. You can visualize positional encoding as both heat maps and points rotating on rings, and in this case the dimension of word embedding is 256, and the maximum length of sentences is 50.

*In fact some implementations use different type of positional encoding, as you can see in the codes below. In this case, embedding vectors are roughly divided into two parts, and each part is encoded with different sine waves. I have been using a metaphor of rotating rings or gears in this article to explain positional encoding, but to be honest that is not necessarily true of all the types of Transformer implementation. Some papers compare different types of pairs of positional encoding. The most important point is, Transformer models is navigated to learn positions of tokens with certain types of mathematical patterns.

[References]

[1] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, “Attention Is All You Need” (2017)

[2] “Transformer model for language understanding,” Tensorflow Core
https://www.tensorflow.org/overview

[3] Jay Alammar, “The Illustrated Transformer,”
http://jalammar.github.io/illustrated-transformer/

[4] “Stanford CS224N: NLP with Deep Learning | Winter 2019 | Lecture 14 – Transformers and Self-Attention,” stanfordonline, (2019)

[5]Harada Tatsuya, “Machine Learning Professional Series: Image Recognition,” (2017), pp. 191-193

[6] Amirhossein Kazemnejad, “Transformer Architecture: The Positional Encoding
Let’s use sinusoidal functions to inject the order of words in our model”, Amirhossein Kazemnejad’s Blog, (2019)

[7] Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko, “End-to-End Object Detection with Transformers,” (2020)

[8]中西 啓、「【第5回】機械式暗号機の傑作～エニグマ登場～」、HH News & Reports, (2011)

[9]中西 啓、「【第6回】エニグマ解読～第2次世界大戦とコンピュータの誕生～」、HH News & Reports, (2011)

[10]Tsuboi Yuuta, Unno Yuuya, Suzuki Jun, “Machine Learning Professional Series: Natural Language Processing with Deep Learning,” (2017), pp. 91-94

[11]”Stanford CS224N: NLP with Deep Learning | Winter 2019 | Lecture 8 – Translation, Seq2Seq, Attention”, stanfordonline, (2019)

* I make study materials on machine learning, sponsored by DATANOMIQ. I do my best to make my content as straightforward but as precise as possible. I include all of my reference sources. If you notice any mistakes in my materials, including grammatical errors, please let me know (email: yasuto.tamura@datanomiq.de). And if you have any advice for making my materials more understandable to learners, I would appreciate hearing it.

## Multi-head attention mechanism: “queries”, “keys”, and “values,” over and over again

*A comment added on 04/05/2022: Thanks to a comment by Mr. Maier, I found a major mistake in my visualization. To be concrete, there is a mistake in expressing how to get each colored divided group of tokens by applying linear transformations. That corresponds to the section 3.2.2 in the paper “Attention Is All You Need.” There would be no big differences in the main point of this article, the relations of keys, queries, and values, but please bear that in your mind if you need Transformer at a practical work. Besides checking the implementation by Tensorflow, I will soon prepare a modified version of visualization. For further details, please see comments at the bottom of this article.

This is the third article of my article series named “Instructions on Transformer for people outside NLP field, but with examples of NLP.”

In the last article, I explained how attention mechanism works in simple seq2seq models with RNNs, and it basically calculates correspondences of the hidden state at every time step, with all the outputs of the encoder. However I would say the attention mechanisms of RNN seq2seq models use only one standard for comparing them. Using only one standard is not enough for understanding languages, especially when you learn a foreign language. You would sometimes find it difficult to explain how to translate a word in your language to another language. Even if a pair of languages are very similar to each other, translating them cannot be simple switching of vocabulary. Usually a single token in one language is related to several tokens in the other language, and vice versa. How they correspond to each other depends on several criteria, for example “what”, “who”, “when”, “where”, “why”, and “how”. It is easy to imagine that you should compare tokens with several criteria.

Transformer model was first introduced in the original paper named “Attention Is All You Need,” and from the title you can easily see that attention mechanism plays important roles in this model. When you learn about Transformer model, you will see the figure below, which is used in the original paper on Transformer.  This is the simplified overall structure of one layer of Transformer model, and you stack this layer N times. In one layer of Transformer, there are three multi-head attention, which are displayed as boxes in orange. These are the very parts which compare the tokens on several standards. I made the head article of this article series inspired by this multi-head attention mechanism.

When you learn Transformer model, I recommend you first to pay attention to multi-head attention. And when you learn multi-head attentions, before seeing what scaled dot-product attention is, you should understand the whole structure of multi-head attention, which is at the right side of the figure above. In order to calculate attentions with a “query”, as I said in the last article, “you compare the ‘query’ with the ‘keys’ and get scores/weights for the ‘values.’ Each score/weight is in short the relevance between the ‘query’ and each ‘key’. And you reweight the ‘values’ with the scores/weights, and take the summation of the reweighted ‘values’.” Sooner or later, you will notice I would be just repeating these phrases over and over again throughout this article, in several ways.

*Even if you are not sure what “reweighting” means in this context, please keep reading. I think you would little by little see what it means especially in the next section.

The overall process of calculating multi-head attention, displayed in the figure above, is as follows (Please just keep reading. Please do not think too much.): first you split the V: “values”, K: “keys”, and Q: “queries”, and second you transform those divided “values”, “keys”, and “queries” with densely connected layers (“Linear” in the figure). Next you calculate attention weights and reweight the “values” and take the summation of the reiweighted “values”, and you concatenate the resulting summations. At the end you pass the concatenated “values” through another densely connected layers. The mechanism of scaled dot-product attention is just a matter of how to concretely calculate those attentions and reweight the “values”.

*In the last article I briefly mentioned that “keys” and “queries” can be in the same language. They can even be the same sentence in the same language, and in this case the resulting attentions are called self-attentions, which we are mainly going to see. I think most people calculate “self-attentions” unconsciously when they speak. You constantly care about what “she”, “it” , “the”, or “that” refers to in you own sentence, and we can say self-attention is how these everyday processes is implemented.

I think you now have rough insight into how you calculate multi-head attentions. In the next section I am going to explain the process of reweighting the tokens, that is, I am finally going to explain what those colorful lines in the head image of this article series are.

*Each head is randomly initialized, so they learn to compare tokens with different criteria. The standards might be straightforward like “what” or “who”, or maybe much more complicated. In attention mechanisms in deep learning, you do not need feature engineering for setting such standards.

### 2 Calculating attentions and reweighting “values”

If you have read the last article or if you understand attention mechanism to some extent, you should already know that attention mechanism calculates attentions, or relevance between “queries” and “keys.” In the last article, I showed the idea of weights as a histogram, and in that case the “query” was the hidden state of the decoder at every time step, whereas the “keys” were the outputs of the encoder. In this section, I am going to explain attention mechanism in a more abstract way, and we consider comparing more general “tokens”, rather than concrete outputs of certain networks. In this section each denotes a token, which is usually an embedding vector in practice.

Please remember this mantra of attention mechanism: “you compare the ‘query’ with the ‘keys’ and get scores/weights for the ‘values.’ Each score/weight is in short the relevance between the ‘query’ and each ‘key’. And you reweight the ‘values’ with the scores/weights, and take the summation of the reweighted ‘values’.” The figure below shows an overview of a case where “Michael” is a query. In this case you compare the query with the “keys”, that is, the input sentence “Anthony Hopkins admired Michael Bay as a great director.” and you get the histogram of attentions/weights. Importantly the sum of the weights 1. With the attentions you have just calculated, you can reweight the “values,” which also denote the same input sentence. After that you can finally take a summation of the reweighted values. And you use this summation.

*I have been repeating the phrase “reweighting ‘values’  with attentions,”  but you in practice calculate the sum of those reweighted “values.”

Assume that compared to the “query”  token “Michael”, the weights of the “key” tokens “Anthony”, “Hopkins”, “admired”, “Michael”, “Bay”, “as”, “a”, “great”, and “director.” are respectively 0.06, 0.09, 0.05, 0.25, 0.18, 0.06, 0.09, 0.06, 0.15. In this case the sum of the reweighted token is 0.06″Anthony” + 0.09″Hopkins” + 0.05″admired” + 0.25″Michael” + 0.18″Bay” + 0.06″as” + 0.09″a” + 0.06″great” 0.15″director.”, and this sum is the what wee actually use.

*Of course the tokens are embedding vectors in practice. You calculate the reweighted vector in actual implementation.

You repeat this process for all the “queries.”  As you can see in the figure below, you get summations of 9 pairs of reweighted “values” because you use every token of the input sentence “Anthony Hopkins admired Michael Bay as a great director.” as a “query.” You stack the sum of reweighted “values” like the matrix in purple in the figure below, and this is the output of a one head multi-head attention.

### 3 Scaled-dot product

This section is a only a matter of linear algebra. Maybe this is not even so sophisticated as linear algebra. You just have to do lots of Excel-like operations. A tutorial on Transformer by Jay Alammar is also a very nice study material to understand this topic with simpler examples. I tried my best so that you can clearly understand multi-head attention at a more mathematical level, and all you need to know in order to read this section is how to calculate products of matrices or vectors, which you would see in the first some pages of textbooks on linear algebra.

We have seen that in order to calculate multi-head attentions, we prepare 8 pairs of “queries”, “keys” , and “values”, which I showed in 8 different colors in the figure in the first section. We calculate attentions and reweight “values” independently in 8 different heads, and in each head the reweighted “values” are calculated with this very simple formula of scaled dot-product: . Let’s take an example of calculating a scaled dot-product in the blue head.

At the left side of the figure below is a figure from the original paper on Transformer, which explains one-head of multi-head attention. If you have read through this article so far, the figure at the right side would be more straightforward to understand. You divide the input sentence into 8 chunks of matrices, and you independently put those chunks into eight head. In one head, you convert the input matrix by three different fully connected layers, which is “Linear” in the figure below, and prepare three matrices , which are “queries”, “keys”, and “values” respectively.

*Whichever color attention heads are in, the processes are all the same.

*You divide by in the formula. According to the original paper, it is known that re-scaling by is found to be effective. I am not going to discuss why in this article.

As you can see in the figure below, calculating is virtually just multiplying three matrices with the same size (Only K is transposed though). The resulting matrix is the output of the head.

is calculated like in the figure below. The softmax function regularize each row of the re-scaled product , and the resulting matrix is a kind a heat map of self-attentions.

The process of comparing one “query” with “keys” is done with simple multiplication of a vector and a matrix, as you can see in the figure below. You can get a histogram of attentions for each query, and the resulting 9 dimensional vector is a list of attentions/weights, which is a list of blue circles in the figure below. That means, in Transformer model, you can compare a “query” and a “key” only by calculating an inner product. After re-scaling the vectors by dividing them with and regularizing them with a softmax function, you stack those vectors, and the stacked vectors is the heat map of attentions.

You can reweight “values” with the heat map of self-attentions, with simple multiplication. It would be more straightforward if you consider a transposed scaled dot-product . This also should be easy to understand if you know basics of linear algebra.

One column of the resulting matrix () can be calculated with a simple multiplication of a matrix and a vector, as you can see in the figure below. This corresponds to the process or “taking a summation of reweighted ‘values’,” which I have been repeating. And I would like you to remember that you got those weights (blue) circles by comparing a “query” with “keys.”

Again and again, let’s repeat the mantra of attention mechanism together: “you compare the ‘query’ with the ‘keys’ and get scores/weights for the ‘values.’ Each score/weight is in short the relevance between the ‘query’ and each ‘key’. And you reweight the ‘values’ with the scores/weights, and take the summation of the reweighted ‘values’.” If you have been patient enough to follow my explanations, I bet you have got a clear view on how multi-head attention mechanism works.

We have been seeing the case of the blue head, but you can do exactly the same procedures in every head, at the same time, and this is what enables parallelization of multi-head attention mechanism. You concatenate the outputs of all the heads, and you put the concatenated matrix through a fully connected layers.

If you are reading this article from the beginning, I think this section is also showing the same idea which I have repeated, and I bet more or less you no have clearer views on how multi-head attention mechanism works. In the next section we are going to see how this is implemented.

### 4 Tensorflow implementation of multi-head attention

Let’s see how multi-head attention is implemented in the Tensorflow official tutorial. If you have read through this article so far, this should not be so difficult. I also added codes for displaying heat maps of self attentions. With the codes in this Github page, you can display self-attention heat maps for any input sentences in English.

The multi-head attention mechanism is implemented as below. If you understand Python codes and Tensorflow to some extent, I think this part is relatively easy.  The multi-head attention part is implemented as a class because you need to train weights of some fully connected layers. Whereas, scaled dot-product is just a function.

Let’s see a case of using multi-head attention mechanism on a (1, 9, 512) sized input tensor, just as we have been considering in throughout this article. The first axis of (1, 9, 512) corresponds to the batch size, so this tensor is virtually a (9, 512) sized tensor, and this means the input is composed of 9 512-dimensional vectors. In the results below, you can see how the shape of input tensor changes after each procedure of calculating multi-head attention. Also you can see that the output of the multi-head attention is the same as the input, and you get a matrix of attention heat maps of each attention head.

I guess the most complicated part of this implementation above is the split_head() function, especially if you do not understand tensor arithmetic. This part corresponds to splitting the input tensor to 8 different colored matrices as in one of the figures above. If you cannot understand what is going on in the function, I recommend you to prepare a sample tensor as below.

This is just a simple (1, 9, 512) sized tensor with sequential integer elements. The first row (1, 2, …., 512) corresponds to the first input token, and (4097, 4098, … , 4608) to the last one. You should try converting this sample tensor to see how multi-head attention is implemented. For example you can try the operations below.

These operations correspond to splitting the input into 8 heads, whose sizes are all (9, 64). And the second axis of the resulting (1, 8, 9, 64) tensor corresponds to the index of the heads. Thus sample_sentence[0][0] corresponds to the first head, the blue matrix. Some Tensorflow functions enable linear calculations in each attention head, independently as in the codes below.

Very importantly, we have been only considering the cases of calculating self attentions, where all “queries”, “keys”, and “values” come from the same sentence in the same language. However, as I showed in the last article, usually “queries” are in a different language from “keys” and “values” in translation tasks, and “keys” and “values” are in the same language. And as you can imagine, usualy “queries” have different number of tokens from “keys” or “values.” You also need to understand this case, which is not calculating self-attentions. If you have followed this article so far, this case is not that hard to you. Let’s briefly see an example where the input sentence in the source language is composed 9 tokens, on the other hand the output is composed 12 tokens.

As I mentioned, one of the outputs of each multi-head attention class is matrix of attention heat maps, which I displayed as a matrix composed of blue circles in the last section. The the implementation in the Tensorflow official tutorial, I have added codes to display actual heat maps of any input sentences in English.

After running codes in the Github page, you can display heat maps of self attentions. Let’s input the sentence “Anthony Hopkins admired Michael Bay as a great director.” You would get a heat maps like this.

In fact, my toy implementation cannot handle proper nouns such as “Anthony” or “Michael.” Then let’s consider a simple input sentence “He admired her as a great director.” In each layer, you respectively get 8 self-attention heat maps.

I think we can see some tendencies in those heat maps. The heat maps in the early layers, which are close to the input, are blurry. And the distributions of the heat maps come to concentrate more or less diagonally. At the end, presumably they learn to pay attention to the start and the end of sentences.

You should be proud of having been patient, and you passed the most tiresome part of learning Transformer model. You must be ready for making a toy English-German translator in the upcoming articles. Also I am sure you have understood that Michael Bay is a great director, no matter what people say.

### [References]

[1] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, “Attention Is All You Need” (2017)

[2] “Transformer model for language understanding,” Tensorflow Core
https://www.tensorflow.org/overview

[3] “Neural machine translation with attention,” Tensorflow Core
https://www.tensorflow.org/tutorials/text/nmt_with_attention

[4] Jay Alammar, “The Illustrated Transformer,”
http://jalammar.github.io/illustrated-transformer/

[5] “Stanford CS224N: NLP with Deep Learning | Winter 2019 | Lecture 14 – Transformers and Self-Attention,” stanfordonline, (2019)

[6]Tsuboi Yuuta, Unno Yuuya, Suzuki Jun, “Machine Learning Professional Series: Natural Language Processing with Deep Learning,” (2017), pp. 91-94

[7]”Stanford CS224N: NLP with Deep Learning | Winter 2019 | Lecture 8 – Translation, Seq2Seq, Attention”, stanfordonline, (2019)

[8]Rosemary Rossi, “Anthony Hopkins Compares ‘Genius’ Michael Bay to Spielberg, Scorsese,” yahoo! entertainment, (2017)
https://www.yahoo.com/entertainment/anthony-hopkins-transformers-director-michael-bay-guy-genius-010058439.html

* I make study materials on machine learning, sponsored by DATANOMIQ. I do my best to make my content as straightforward but as precise as possible. I include all of my reference sources. If you notice any mistakes in my materials, including grammatical errors, please let me know (email: yasuto.tamura@datanomiq.de). And if you have any advice for making my materials more understandable to learners, I would appreciate hearing it.

## On the difficulty of language: prerequisites for NLP with deep learning

This is the first article of my article series “Instructions on Transformer for people outside NLP field, but with examples of NLP.”

### 1 Preface

This section is virtually just my essay on language. You can skip this if you want to get down on more technical topic.

As I do not study in natural language processing (NLP) field, I would not be able to provide that deep insight into this fast changing deep leaning field throughout my article series. However at least I do understand language is a difficult and profound field, not only in engineering but also in many other study fields. Some people might be feeling that technologies are eliminating languages, or one’s motivations to understand other cultures. First of all, I would like you to keep it in mind that I am not a geek who is trying to turn this multilingual world into a homogeneous one and rebuild Tower of Babel, with deep learning. I would say I am more keen on social or anthropological sides of language.

I think you would think more about languages if you have mastered at least one foreign language. As my mother tongue is Japanese, which is totally different from many other Western languages in terms of characters and ambiguity, I understand translating is not what learning a language is all about. Each language has unique characteristics, and I believe they more or less influence one’s personalities. For example, many Western languages make the verb, I mean the conclusion, of sentences clear in the beginning part of the sentences. That is also true of Chinese, I heard. However in Japanese, the conclusion comes at the end, so that is likely to give an impression that Japanese people are being obscure or indecisive. Also, Japanese sentences usually omit their subjects. In German as well, the conclusion of a sentences tend to come at the end, but I am almost 100% sure that no Japanese people would feel German people make things unclear. I think that comes from the structures of German language, which tends to make the number, verb, relations of words crystal clear.

Let’s take an example to see how obscure Japanese is. A Japanese sentence 「頭が赤い魚を食べる猫」can be interpreted in five ways, depending on where you put emphases on.

Common sense tells you that the sentence is likely to mean the first two cases, but I am sure they can mean those five possibilities. There might be similarly obscure sentences in other languages, but I bet few languages can be as obscure as Japanese. Also as you can see from the last two sentences, you can omit subjects in Japanese. This rule is nothing exceptional. Japanese people usually don’t use subjects in normal conversations. And when you read classical Japanese, which Japanese high school students have to do just like Western students learn some of classical Latin, the writings omit subjects much more frequently.

*However interestingly we have rich vocabulary of subjects. The subject “I” can be translated to 「私」、「僕」、「俺」、「自分」、「うち」etc, depending on your personality, who you are talking to, and the time when it is written in.

I believe one can see the world only in the framework of their language, and it seems one’s personality changes depending on the language they use. I am not sure whether the language originally determines how they think, or how they think forms the language. But at least I would like you to keep it in mind that if you translate a conversation, for example a random conversation at a bar in Berlin, into Japanese, that would linguistically sound Japanese, but not anthropologically. Imagine that such kind of random conversation in Berlin or something is like playing a catch, I mean throwing a ball named “your opinion.” On the other hand,  normal conversations of Japanese people are in stead more of, I would say,  “resonance” of several tuning forks. They do their bests to show that they are listening to each other, by excessively nodding or just repeating “Really?”, but usually it seems hardly any constructive dialogues have been made.

*I sometimes feel you do not even need deep learning to simulate most of such Japanese conversations. Several-line Python codes would be enough.

My point is, this article series is mainly going to cover only a few techniques of NLP in deep learning field: sequence to sequence model (seq2seq model) , and especially Transformer. They are, at least for now, just mathematical models and mappings of a small part of this profound field of language (as far as I can cover in this article series). But still, examples of language would definitely help you understand Transformer model in the long run.

### 2 Tokens and word embedding

*Throughout my article series, “words” just means the normal words you use in daily life. “Tokens” means more general unit of NLP tasks. For example the word “Transformer” might be denoted as a single token “Transformer,” or maybe as a combination of two tokens “Trans” and “former.”

One challenging part of handling language data is its encodings. If you started learning programming in a language other than English, you would have encountered some troubles of using keyboards with different arrangements or with characters. Some comments on your codes in your native languages are sometimes not readable on some software. You can easily get away with that by using only English, but when it comes to NLP you have to deal with this difficulty seriously. How to encode characters in each language should be a first obstacle of NLP. In this article we are going to rely on a library named BPEmb, which provides word embedding in various languages, and you do not have to care so much about encodings in languages all over the world with this library.

In the first section, you might have noticed that Japanese sentence is not separated with spaces like Western languages. This is also true of Chinese language, and that means we need additional tasks of separating those sentences at least into proper chunks of words. This is not only a matter of engineering, but also of some linguistic fields. Also I think many people are not so conscious of how sentences in their native languages are grammatically separated.

The next point is, unlike other scientific data, such as temperature, velocity, voltage, or air pressure, language itself is not measured as numerical data. Thus in order to process language, including English, you first have to map language to certain numerical data, and after some processes you need to conversely map the output numerical data into language data. This section is going to be mainly about one-hot encoding and word embedding, the ways to convert word/token into numerical data. You might already have heard about this

You might have learnt about word embedding to some extent, but I hope you could get richer insight into this topic through this article.

2.1 One-hot encoding

One-hot encoding would be the most straightforward way to encode words/tokens. Assume that you have a dictionary whose size is , and it includes words from “a”, “ablation”, “actually” to “zombie”, “?”, “!”

In a mathematical manner, in order to choose a word out of those words, all you need is a dimensional vector, one of whose elements is , and the others are . When you want to choose the No. i word, which is “indeed” in the example below, its corresponding one-hot vector is , where only the No. i element is . One-hot encoding is also easy to understand, and that’s all. It is easy to imagine that people have already come up with more complicated and better way to encoder words. And one major way to do that is word embedding.

2.2 Word embedding

Source: Francois Chollet, Deep Learning with Python,(2018), Manning

Actually word embedding is related to one-hot encoding, and if you understand how to train a simple neural network, for example densely connected layers, you would understand word embedding easily. The key idea of word embedding is denoting each token with a dimensional vector, whose dimension is fewer than the vocabulary size . The elements of the resulting word embedding vector are real values, I mean not only 0 or 1. Obviously you can encode much richer variety of tokens with such vectors. The figure at the left side is from “Deep Learning with Python” by François Chollet, and I think this is an almost perfect and simple explanation of the comparison of one-hot encoding and word embedding. But the problem is how to get such convenient vectors. The answer is very simple: you have only to train a network whose inputs are one-hot vector of the vocabulary.

The figure below is a simplified model of word embedding of a certain word. When the word is input into a neural network, only the corresponding element of the one-hot vector is 1, and that virtually means the very first input layer is composed of one neuron whose value is 1. And the only one neuron propagates to the next D dimensional embedding layer. These weights are the very values which most other study materials call “an embedding vector.”

When you input each word into a certain network, for example RNN or Transformer, you map the input one-hot vector into the embedding layer/vector. The examples in the figure are how inputs are made when the input sentences are “You’ve got the touch” and “You’ve got the power.”   Assume that you have a dictionary of one-hot encoding, whose vocabulary is {“the”, “You’ve”, “Walberg”, “touch”, “power”, “Nights”, “got”, “Mark”, “Boogie”}, and the dimension of word embeding is 6. In this case . When the inputs are “You’ve got the touch” or “You’ve got the power” , you put the one-hot vector corresponding to “You’ve”, “got”, “the”, “touch” or “You’ve”, “got”, “the”, “power” sequentially every time step .

In order to get word embedding of certain vocabulary, you just need to train the network. We know that the words “actually” and “indeed” are used in similar ways in writings. Thus when we propagate those words into the embedding layer, we can expect that those embedding layers are similar. This is how we can mathematically get effective word embedding of certain vocabulary.

More interestingly, if word embedding is properly trained, you can mathematically “calculate” words. For example, , .

*I have tried to demonstrate this type of calculation on several word embedding, but none of them seem to work well. At least you should keep it in mind that word embedding learns complicated linear relations between words.

I should explain word embedding techniques such as word2vec in detail, but the main focus of this article is not NLP, so the points I have mentioned are enough to understand Transformer model with NLP examples in the upcoming articles.

### 3 Language model

*I am not sure which algorithm is used in which services. That must be too fast changing and competitive for me to catch up.

As I mentioned in the first article series on RNN, a sentence is usually processed as sequence data in NLP. One single sentence is denoted as , a list of vectors. The vectors are usually embedding vectors, and the is the index of the order of tokens. For example the sentence “You’ve go the power.” can be expressed as , where denote “You’ve”, “got”, “the”, “power”, “.” respectively. In this case .

In practice a sentence usually includes two tokens and at the beginning and the end of the sentence. They mean “Beginning Of Sentence” and “End Of Sentence” respectively. Thus in many cases . and are also both vectors, at least in the Tensorflow tutorial.

is the probability of incidence of the sentence. But it is easy to imagine that it would be very hard to directly calculate how likely the sentence appears out of all possible sentences. I would rather say it is impossible. Thus instead in NLP we calculate the probability as a product of the probability of incidence or a certain word, given all the words so far. When you’ve got the words so far, the probability of the incidence of , given the context is  . is a probability of the the sentence being , and the probability of being can be decomposed this way: .

Just as well .

Hence, the general probability of incidence of a sentence is .

Let be and be . Plus, let be , then . Language models calculate which words to come sequentially in this way.

Here’s a question: how would you evaluate a language model?

I would say the answer is, when the language model generates words, the more confident the language model is, the better the language model is. Given a context, when the distribution of the next word is concentrated on a certain word, we can say the language model is confident about which word to come next, given the context.

*For some people, it would be more understandable to call this “entropy.”

Let’s take the vocabulary {“the”, “You’ve”, “Walberg”, “touch”, “power”, “Nights”, “got”, “Mark”, “Boogie”} as an example. Assume that . Given a context , the probability of incidence of is . In the figure below, the distribution at the left side is less confident because probabilities do not spread widely, on the other hand the one at the right side is more confident that next word is “got” because the distribution concentrates on “got”.

*You have to keep it in mind that the sum of all possible probability is , that is, .

While the language model generating the sentence “BOS You’ve got the touch EOS”, it is better if the language model keeps being confident. If it is confident, gets higher. Thus gets lower, where usually or .

This is how to measure how confident language models are, and the indicator of the confidence is called perplexity. Assume that you have a data set for evaluation , which is composed of sentences in total. Each sentence has tokens in total excluding . And let be the size of the vocabulary of the language model. Then the perplexity of the language model is , where . The is usually or .

For example, assume that is vocabulary {“the”, “You’ve”, “Walberg”, “touch”, “power”, “Nights”, “got”, “Mark”, “Boogie”}. Also assume that the evaluation data set for perplexity of a language model is , where . In this case . I have already showed you how to calculate the perplexity of the sentence “You’ve got the touch.” above. You just need to do a similar thing on another sentence “You’ve got the power”, and then you can get the perplexity of the language model.

*If the network is not properly trained, it would also be confident of generating wrong outputs. However, such network still would give high perplexity because it is “confident” at any rate. I’m sorry I don’t know how to tackle the problem. Please let me put this aside, and let’s get down on Transformer model soon.

### Appendix

Let’s see how word embedding is implemented with a very simple example in the official Tensorflow tutorial. It is a simple binary classification task on IMDb Dataset. The dataset is composed to comments on movies by movie critics, and you have only to classify if the commentary is positive or negative about the movie. For example when you get you get an input “To be honest, Michael Bay is a terrible as an action film maker. You cannot understand what is going on during combat scenes, and his movies rely too much on advertisements. I got a headache when Mark Walberg used a Chinese cridit card in Texas. However he is very competent when it comes to humorous scenes. He is very talented as a comedy director, and I have to admit I laughed a lot.“, the neural netowork has to judge whether the statement is positive or negative.

This networks just takes an average of input embedding vectors and regress it into a one dimensional value from 0 to 1. The shape of embedding layer is (8185, 16). Weights of neural netowrks are usually implemented as matrices, and you can see that each row of the matrix corresponds to emmbedding vector of each token.

*It is easy to imagine that this technique is problematic. This network virtually taking a mean of input embedding vectors. That could mean if the input sentence includes relatively many tokens with negative meanings, it is inclined to be classified as negative. But for example, if the sentence is “This masterpiece is a dark comedy by Charlie Chaplin which depicted stupidity of the evil tyrant gaining power in the time. It thoroughly mocked Germany in the time as an absurd group of fanatics, but such propaganda could have never been made until ‘Casablanca.'” , this can be classified as negative, because only the part “masterpiece” is positive as a token, and there are much more words with negative meanings themselves.

The official Tensorflow tutorial provides visualization of word embedding with Embedding Projector, but I would like you to take more control over the data by yourself. Please just copy and paste the codes below, installing necessary libraries. You would get a map of vocabulary used in the text classification task. It seems you cannot find clear tendency of the clusters of the tokens. You can try other dimension reduction methods to get maps of the vocabulary by for example using Scikit Learn.

### [References]

[1] “Word embeddings” Tensorflow Core
https://www.tensorflow.org/tutorials/text/word_embeddings

[2]Tsuboi Yuuta, Unno Yuuya, Suzuki Jun, “Machine Learning Professional Series: Natural Language Processing with Deep Learning,” (2017), pp. 43-64, 72-85, 91-94

[3]”Stanford CS224N: NLP with Deep Learning | Winter 2019 | Lecture 8 – Translation, Seq2Seq, Attention”, stanfordonline, (2019)

[4] Francois Chollet, Deep Learning with Python,(2018), Manning , pp. 178-185

[5]”2.2. Manifold learning,” scikit-learn
https://scikit-learn.org/stable/modules/manifold.html

* I make study materials on machine learning, sponsored by DATANOMIQ. I do my best to make my content as straightforward but as precise as possible. I include all of my reference sources. If you notice any mistakes in my materials, including grammatical errors, please let me know (email: yasuto.tamura@datanomiq.de). And if you have any advice for making my materials more understandable to learners, I would appreciate hearing it.

## Visual Question Answering with Keras – Part 2: Making Computers Intelligent to answer from images

### Making Computers Intelligent to answer from images

This is my second blog on Visual Question Answering, in the last blog, I have introduced to VQA, available datasets and some of the real-life applications of VQA. If you have not gone through then I would highly recommend you to go through it. Click here for more details about it.

In this blog post, I will walk through the implementation of VQA in Keras.

You can download the dataset from here: https://visualqa.org/index.html. All my experiments were performed with VQA v2 and I have used a very tiny subset of entire dataset i.e all samples for training and testing from the validation set.

1. Preprocessing Data
2. Process overview for VQA
3. Data Preprocessing – Images
4. Data Preprocessing through the spaCy library- Questions
5. Model Architecture
6. Defining model parameters
7. Evaluating the model
8. Final Thought
9. References

NOTE: The purpose of this blog is not to get the state-of-art performance on VQA. But the idea is to get familiar with the concept. All my experiments were performed with the validation set only.

Full code on my Github here.

### 1. Preprocessing Data:

If you have downloaded the dataset then the question and answers (called as annotations) are in JSON format. I have provided the code to extract the questions, annotations and other useful information in my Github repository. All extracted information is stored in .txt file format. After executing code the preprocessing directory will have the following structure.

All text files will be used for training.

### 2. Process overview for VQA:

As we have discussed in previous post visual question answering is broken down into 2 broad-spectrum i.e. vision and text.  I will represent the Neural Network approach to this problem using the Convolutional Neural Network (for image data) and Recurrent Neural Network(for text data).

If you are not familiar with RNN (more precisely LSTM) then I would highly recommend you to go through Colah’s blog and Andrej Karpathy blog. The concepts discussed in this blogs are extensively used in my post.

The main idea is to get features for images from CNN and features for the text from RNN and finally combine them to generate the answer by passing them through some fully connected layers. The below figure shows the same idea.

I have used VGG-16 to extract the features from the image and LSTM layers to extract the features from questions and combining them to get the answer.

### 3. Data Preprocessing – Images:

Images are nothing but one of the input to our model. But as you already may know that before feeding images to the model we need to convert into the fixed-size vector.

So we need to convert every image into a fixed-size vector then it can be fed to the neural network. For this, we will use the VGG-16 pretrained model. VGG-16 model architecture is trained on millions on the Imagenet dataset to classify the image into one of 1000 classes. Here our task is not to classify the image but to get the bottleneck features from the second last layer.

Hence after removing the softmax layer, we get a 4096-dimensional vector representation (bottleneck features) for each image.

Image Source: https://www.cs.toronto.edu/~frossard/post/vgg16/

For the VQA dataset, the images are from the COCO dataset and each image has unique id associated with it. All these images are passed through the VGG-16 architecture and their vector representation is stored in the “.mat” file along with id. So in actual, we need not have to implement VGG-16 architecture instead we just do look up into file with the id of the image at hand and we will get a 4096-dimensional vector representation for the image.

### 4. Data Preprocessing through the spaCy library- Questions:

spaCy is a free, open-source library for advanced Natural Language Processing (NLP) in Python. As we have converted images into a fixed 4096-dimensional vector we also need to convert questions into a fixed-size vector representation. For installing spaCy click here

You might know that for training word embeddings in Keras we have a layer called an Embedding layer which takes a word and embeds it into a higher dimensional vector representation. But by using the spaCy library we do not have to train the get the vector representation in higher dimensions.

This model is actually trained on billions of tokens of the large corpus. So we just need to call the vector method of spaCy class and will get vector representation for word.

After fitting, the vector method on tokens of each question will get the 300-dimensional fixed representation for each word.

### 5. Model Architecture:

In our problem the input consists of two parts i.e an image vector, and a question, we cannot use the Sequential API of the Keras library. For this reason, we use the Functional API which allows us to create multiple models and finally merge models.

The below picture shows the high-level architecture idea of submodules of neural network.

After concatenating the 2 different models the summary will look like the following.

The below plot helps us to visualize neural network architecture and to understand the two types of input:

### 6. Defining model parameters:

The hyperparameters that we are going to use for our model is defined as follows:

If you know what this parameter means then you can play around it and can get better results.

Time Taken: I used the GPU on https://colab.research.google.com and hence it took me approximately 2 hours to train the model for 5 epochs. However, if you train it on a PC without GPU, it could take more time depending on the configuration of your machine.

### 7. Evaluating the model:

Since I have used the very small dataset for performing these experiments I am not able to get very good accuracy. The below code will calculate the accuracy of the model.

Since I have trained a model multiple times with different parameters you will not get the same accuracy as me. If you want you can directly download mode.h5 file from my google drive.

### 8. Final Thoughts:

One of the interesting thing about VQA is that it a completely new field. So there is absolutely no end to what you can do to solve this problem. Below are some tips while replicating the code.

1. Start with a very small subset of data: When you start implementing I suggest you start with a very small amount of data. Because once you are ready with the whole setup then you can scale it any time.
2. Understand the code: Understanding code line by line is very much helpful to match your theoretical knowledge. So for that, I suggest you can take very few samples(maybe 20 or less) and run a small chunk (2 to 3 lines) of code to get the functionality of each part.
3. Be patient: One of the mistakes that I did while starting with this project was to do everything at one go. If you get some error while replicating code spend 4 to 5 days harder on that. Even after that if you won’t able to solve, I would suggest you resume after a break of 1 or 2 days.

VQA is the intersection of NLP and CV and hopefully, this project will give you a better understanding (more precisely practically) with most of the deep learning concepts.

If you want to improve the performance of the model below are few tips you can try:

1. Use larger datasets
2. Try Building more complex models like Attention, etc
3. Try using other pre-trained word embeddings like Glove
4. Try using a different architecture
5. Do more hyperparameter tuning

The list is endless and it goes on.

In the blog, I have not provided the complete code you can get it from my Github repository.

## Einleitung

Aufgrund vielfältiger potenzieller Geschäftschancen, die Machine Learning bietet, arbeiten mittlerweile viele Unternehmen an Initiativen für datengetriebene Innovationen. Dabei gründen sie Analytics-Teams, schreiben neue Stellen für Data Scientists aus, bauen intern Know-how auf und fordern von der IT-Organisation eine Infrastruktur für “heavy” Data Engineering & Processing samt Bereitstellung einer Analytics-Toolbox ein. Für IT-Architekten warten hier spannende Herausforderungen, u.a. bei der Zusammenarbeit mit interdisziplinären Teams, deren Mitglieder unterschiedlich ausgeprägte Kenntnisse im Bereich Machine Learning (ML) und Bedarfe bei der Tool-Unterstützung haben. Einige Überlegungen sind dabei: Sollen Data Scientists mit ML-Toolkits arbeiten und eigene maßgeschneiderte Algorithmen nur im Ausnahmefall entwickeln, damit später Herausforderungen durch (unkonventionelle) Integrationen vermieden werden? Machen ML-Funktionen im seit Jahren bewährten ETL-Tool oder in der Datenbank Sinn? Sollen ambitionierte Fachanwender künftig selbst Rohdaten aufbereiten und verknüpfen, um auf das präparierte Dataset einen populären Algorithmus anzuwenden und die Ergebnisse selbst interpretieren? Für die genannten Fragestellungen warten junge & etablierte Software-Hersteller sowie die Open Source Community mit “All-in-one”-Lösungen oder Machine Learning-Erweiterungen auf. Vor dem Hintergrund des Data Science Prozesses, der den Weg eines ML-Modells von der experimentellen Phase bis zur Operationalisierung beschreibt, vergleicht dieser Artikel ausgewählte Ansätze (Notebooks für die Datenanalyse, Machine Learning-Komponenten in ETL- und Datenvisualisierungs­werkzeugen vs. Speziallösungen für Machine Learning) und betrachtet mögliche Einsatzbereiche und Integrationsaspekte.

## Data Science Prozess und Teams

Im Zuge des Big Data-Hypes kamen neben Design-Patterns für Big Data- und Analytics-Architekturen auch Begriffsdefinitionen auf, die Disziplinen wie Datenintegration von Data Engineering und Data Science vonein­ander abgrenzen [1]. Prozessmodelle, wie das ab 1996 im Rahmen eines EU-Förderprojekts entwickelte CRISP-DM (CRoss-Industry Standard Process for Data Mining) [2], und Best Practices zur Organisation erfolgreich arbeitender Data Science Teams [3] weisen dabei die Richtung, wie Unternehmen das Beste aus den eigenen Datenschätzen herausholen können. Die Disziplin Data Science beschreibt den, an ein wissenschaftliches Vorgehen angelehnten, Prozess der Nutzung von internen und externen Datenquellen zur Optimierung von Produkten, Dienstleistungen und Prozessen durch die Anwendung statistischer und mathematischer Modelle. Bild 1 stellt in einem Schwimmbahnen-Diagramm einzelne Phasen des Data Science Prozesses den beteiligten Funktionen gegenüber und fasst Erfahrungen aus der Praxis zusammen [5]. Dabei ist die Intensität bei der Zusammenarbeit zwischen Data Scientists und System Engineers insbesondere bei Vorbereitung und Bereitstellung der benötigten Datenquellen und später bei der Produktivsetzung des Ergebnisses hoch. Eine intensive Beanspruchung der Server-Infrastruktur ist in allen Phasen gegeben, bei denen Hands-on (und oft auch massiv parallel) mit dem Datenpool gearbeitet wird, z.B. bei Datenaufbereitung, Training von ML Modellen etc.

Abbildung 1: Beteiligung und Interaktion von Fachbereichs-/IT-Funktionen mit dem Data Science Team

Mitarbeiter vom Technologie-Giganten Google haben sich reale Machine Learning-Systeme näher angesehen und festgestellt, dass der Umsetzungsaufwand für den eigentlichen Kern (= der ML-Code, siehe den kleinen schwarzen Kasten in der Mitte von Bild 2) gering ist, wenn man dies mit der Bereitstellung der umfangreichen und komplexen Infrastruktur inklusive Managementfunktionen vergleicht [4].

Abbildung 2: Versteckte technische Anforderungen in maschinellen Lernsystemen

## Konzeptionelle Architektur für Machine Learning und Analytics

Die Nutzung aller verfügbaren Daten für Analyse, Durchführung von Data Science-Projekten, mit den daraus resultierenden Maßnahmen zur Prozessoptimierung und -automatisierung, bedeutet für Unternehmen sich neuen Herausforderungen zu stellen: Einführung neuer Technologien, Anwendung komplexer mathematischer Methoden sowie neue Arbeitsweisen, die in dieser Form bisher noch nicht dagewesen sind. Für IT-Architekten gibt es also reichlich Arbeit, entweder um eine Data Management-Plattform neu aufzubauen oder um das bestehende Informationsmanagement weiterzuentwickeln. Bild 3 zeigt hierzu eine vierstufige Architektur nach Gartner [6], ausgerichtet auf Analytics und Machine Learning.

Abbildung 3: Konzeptionelle End-to-End Architektur für Machine Learning und Analytics

Was hat sich im Vergleich zu den traditionellen Data Warehouse- und Business Intelligence-Architekturen aus den 1990er Jahren geändert? Denkt man z.B. an die Präzisionsfertigung eines komplexen Produkts mit dem Ziel, den Ausschuss weiter zu senken und in der Produktionslinie eine höhere Produktivitätssteigerung (Kennzahl: OEE, Operational Equipment Efficiency) erzielen zu können: Die an der Produktherstellung beteiligten Fertigungsmodule (Spezialmaschinen) messen bzw. detektieren über zahlreiche Sensoren Prozesszustände, speicherprogrammierbare Steuerungen (SPS) regeln dazu die Abläufe und lassen zu Kontrollzwecken vom Endprodukt ein oder mehrere hochauflösende Fotos aufnehmen. Bei diesem Szenario entsteht eine Menge interessanter Messdaten, die im operativen Betrieb häufig schon genutzt werden. Z.B. für eine Echtzeitalarmierung bei Über- oder Unterschreitung von Schwellwerten in einem vorher definierten Prozessfenster. Während früher vielleicht aus Kostengründen nur Statusdaten und Störungsinformationen den Weg in relationale Datenbanken fanden, hebt man heute auch Rohdaten, z.B. Zeitreihen (Kraftwirkung, Vorschub, Spannung, Frequenzen,…) für die spätere Analyse auf.

Bezogen auf den Bereich Acquire bewältigt die IT-Architektur in Bild 3 nun Aufgaben, wie die Übernahme und Speicherung von Maschinen- und Sensordaten, die im Millisekundentakt Datenpunkte erzeugen. Während IoT-Plattformen das Registrieren, Anbinden und Management von Hunderten oder Tausenden solcher datenproduzierender Geräte („Things“) erleichtern, beschreibt das zugehörige IT-Konzept den Umgang mit Protokollen wie MQTT, OPC-UA, den Aufbau und Einsatz einer Messaging-Plattform für Publish-/Subscribe-Modelle (Pub/Sub) zur performanten Weiterverarbeitung von Massendaten im JSON-Dateiformat. Im Bereich Organize etablieren sich neben relationalen Datenbanken vermehrt verteilte NoSQL-Datenbanken zum Persistieren eingehender Datenströme, wie sie z.B. im oben beschriebenen Produktionsszenario entstehen. Für hochauflösende Bilder, Audio-, Videoaufnahmen oder andere unstrukturierte Daten kommt zusätzlich noch Object Storage als alternative Speicherform in Frage. Neben der kostengünstigen und langlebigen Datenauf­bewahrung ist die Möglichkeit, einzelne Objekte mit Metadaten flexibel zu beschreiben, um damit später die Auffindbarkeit zu ermöglichen und den notwendigen Kontext für die Analysen zu geben, hier ein weiterer Vorteil. Mit dem richtigen Technologie-Mix und der konsequenten Umsetzung eines Data Lake– oder Virtual Data Warehouse-Konzepts gelingt es IT-Architekten, vielfältige Analytics Anwendungsfälle zu unterstützen.

Im Rahmen des Data Science Prozesses spielt, neben der sicheren und massenhaften Datenspeicherung sowie der Fähigkeit zur gleichzeitigen, parallelen Verarbeitung großer Datenmengen, das sog. Feature-Engineering eine wichtige Rolle. Dazu wieder ein Beispiel aus der maschinellen Fertigung: Mit Hilfe von Machine Learning soll nach unbekannten Gründen für den zu hohen Ausschuss gefunden werden. Was sind die bestimmenden Faktoren dafür? Beeinflusst etwas die Maschinenkonfiguration oder deuten Frequenzveränderungen bei einem Verschleißteil über die Zeit gesehen auf ein Problem hin? Maschine und Sensoren liefern viele Parameter als Zeitreihendaten, aber nur einige davon sind – womöglich nur in einer bestimmten Kombination – für die Aufgabenstellung wirklich relevant. Daher versuchen Data Scientists bei der Feature-Entwicklung die Vorhersage- oder Klassifikationsleistung der Lernalgorithmen durch Erstellen von Merkmalen aus Rohdaten zu verbessern und mit diesen den Lernprozess zu vereinfachen. Die anschließende Feature-Auswahl wählt bei dem Versuch, die Anzahl von Dimensionen des Trainingsproblems zu verringern, die wichtigste Teilmenge der ursprünglichen Daten-Features aus. Aufgrund dieser und anderer Arbeitsschritte, wie z.B. Auswahl und Training geeigneter Algorithmen, ist der Aufbau eines Machine Learning Modells ein iterativer Prozess, bei dem Data Scientists dutzende oder hunderte von Modellen bauen, bis die Akzeptanzkriterien für die Modellgüte erfüllt sind. Aus technischer Sicht sollte die IT-Architektur auch bei der Verwaltung von Machine Learning Modellen bestmöglich unterstützen, z.B. bei Modell-Versionierung, -Deployment und -Tracking in der Produktions­umgebung oder bei der Automatisierung des Re-Trainings.

Die Bereiche Analyze und Deliver zeigen in Bild 3 einige bekannte Analysefähigkeiten, wie z.B. die Bereitstellung eines Standardreportings, Self-service Funktionen zur Geschäftsplanung sowie Ad-hoc Analyse und Exploration neuer Datasets. Data Science-Aktivitäten können etablierte Business Intelligence-Plattformen inhaltlich ergänzen, in dem sie durch neuartige Kennzahlen, das bisherige Reporting „smarter“ machen und ggf. durch Vorhersagen einen Blick in die nahe Zukunft beisteuern. Machine Learning-as-a-Service oder Machine Learning-Produkte sind alternative Darreichungsformen, um Geschäftsprozesse mit Hilfe von Analytik zu optimieren: Z.B. integriert in einer Call Center-Applikation, die mittels Churn-Indikatoren zu dem gerade anrufenden erbosten Kunden einen Score zu dessen Abwanderungswilligkeit zusammen mit Handlungsempfehlungen (Gutschein, Rabatt) anzeigt. Den Kunden-Score oder andere Risikoeinschätzungen liefert dabei eine Service Schnittstelle, die von verschiedenen unternehmensinternen oder auch externen Anwendungen (z.B. Smartphone-App) eingebunden und in Echtzeit angefragt werden kann. Arbeitsfelder für die IT-Architektur wären in diesem Zusammenhang u.a. Bereitstellung und Betrieb (skalierbarer) ML-Modelle via REST API’s in der Produktions­umgebung inklusive Absicherung gegen unerwünschten Zugriff.

## Ein klassischer Ansatz: Datenanalyse und Machine Learning mit Jupyter Notebook & Python

Jupyter ist ein Kommandozeileninterpreter zum interaktiven Arbeiten mit der Programmiersprache Python. Es handelt sich dabei nicht nur um eine bloße Erweiterung der in Python eingebauten Shell, sondern um eine Softwaresuite zum Entwickeln und Ausführen von Python-Programmen. Funktionen wie Introspektion, Befehlszeilenergänzung, Rich-Media-Einbettung und verschiedene Editoren (Terminal, Qt-basiert oder browserbasiert) ermöglichen es, Python-Anwendungen als auch Machine Learning-Projekte komfortabel zu entwickeln und gleichzeitig zu dokumentieren. Datenanalysten sind bei der Arbeit mit Juypter nicht auf Python als Programmiersprache begrenzt, sondern können ebenso auch sog. Kernels für Julia, R und vielen anderen Sprachen einbinden. Ein Jupyter Notebook besteht aus einer Reihe von “Zellen”, die in einer Sequenz angeordnet sind. Jede Zelle kann entweder Text oder (Live-)Code enthalten und ist beliebig verschiebbar. Texte lassen sich in den Zellen mit einer einfachen Markup-Sprache formatieren, komplexe Formeln wie mit einer Ausgabe in LaTeX darstellen. Code-Zellen enthalten Code in der Programmiersprache, die dem aktiven Notebook über den entsprechenden Kernel (Python 2 Python 3, R, etc.) zugeordnet wurde. Bild 4 zeigt auszugsweise eine Analyse historischer Hauspreise in Abhängigkeit ihrer Lage in Kalifornien, USA (Daten und Notebook sind öffentlich erhältlich [7]). Notebooks erlauben es, ganze Machine Learning-Projekte von der Datenbeschaffung bis zur Evaluierung der ML-Modelle reproduzierbar abzubilden und lassen sich gut versionieren. Komplexe ML-Modelle können in Python mit Hilfe des Pickle Moduls, das einen Algorithmus zur Serialisierung und De-Serialisierung implementiert, ebenfalls transportabel gemacht werden.

Abbildung 4: Datenbeschaffung, Inspektion, Visualisierung und ML Modell-Training in einem Jupyter Notebook (Pro-grammiersprache: Python)

Ein Problem, auf das man bei der praktischen Arbeit mit lokalen Jupyter-Installationen schnell stößt, lässt sich mit dem “works on my machine”-Syndrom bezeichnen. Kleine Data Sets funktionieren problemlos auf einem lokalen Rechner, wenn sie aber auf die Größe des Produktionsdatenbestandes migriert werden, skaliert das Einlesen und Verarbeiten aller Daten mit einem einzelnen Rechner nicht. Aufgrund dieser Begrenzung liegt der Aufbau einer server-basierten ML-Umgebung mit ausreichend Rechen- und Speicherkapazität auf der Hand. Dabei ist aber die Einrichtung einer solchen ML-Umgebung, insbesondere bei einer on-premise Infrastruktur, eine Herausforderung: Das Infrastruktur-Team muss physische Server und/oder virtuelle Maschinen (VM’s) auf Anforderung bereitstellen und integrieren. Dieser Ansatz ist aufgrund vieler manueller Arbeitsschritte zeitaufwändig und fehleranfällig. Mit dem Einsatz Cloud-basierter Technologien vereinfacht sich dieser Prozess deutlich. Die Möglichkeit, Infrastructure on Demand zu verwenden und z.B. mit einem skalierbaren Cloud-Data Warehouse zu kombinieren, bietet sofortigen Zugriff auf Rechen- und Speicher-Ressourcen, wann immer sie benötigt werden und reduziert den administrativen Aufwand bei Einrichtung und Verwaltung der zum Einsatz kommenden ML-Software. Bild 5 zeigt den Code-Ausschnitt aus einem Jupyter Notebook, das im Rahmen des Cloud Services Amazon SageMaker bereitgestellt wird und via PySpark Kernel auf einen Multi-Node Apache Spark Cluster (in einer Amazon EMR-Umgebung) zugreift. In diesem Szenario wird aus einem Snowflake Cloud Data Warehouse ein größeres Data Set mit 220 Millionen Datensätzen via Spark-Connector komplett in ein Spark Dataframe geladen und im Spark Cluster weiterverarbeitet. Den vollständigen Prozess inkl. Einrichtung und Konfiguration aller Komponenten, beschreibt eine vierteilige Blog-Serie [8]). Mit Spark Cluster sowie Snowflake stehen für sich genommen zwei leistungsfähige Umgebungen für rechenintensive Aufgaben zur Verfügung. Mit dem aktuellen Snowflake Connector für Spark ist eine intelligente Arbeitsteilung mittels Query Pushdown erreichbar. Dabei entscheidet Spark’s optimizer (Catalyst), welche Aufgaben (Queries) aufgrund der effizienteren Verarbeitung an Snowflake delegiert werden [9].

Abbildung 5: Jupyter Notebook in der Cloud – integriert mit Multi-Node Spark Cluster und Snowflake Cloud Data Warehouse

## Welches Machine Learning Framework für welche Aufgabenstellung?

Bevor die nächsten Abschnitte weitere Werkzeuge und Technologien betrachten, macht es nicht nur für Data Scientists sondern auch für IT-Architekten Sinn, zunächst einen Überblick auf die derzeit verfügbaren Machine Learning Frameworks zu bekommen. Aus Architekturperspektive ist es wichtig zu verstehen, welche Aufgabenstellungen die jeweiligen ML-Frameworks adressieren, welche technischen Anforderungen und ggf. auch Abhängigkeiten zu den verfügbaren Datenquellen bestehen. Ein gemeinsamer Nenner vieler gescheiterter Machine Learning-Projekte ist häufig die Auswahl des falschen Frameworks. Ein Beispiel: TensorFlow ist aktuell eines der wichtigsten Frameworks zur Programmierung von neuronalen Netzen, Deep Learning Modellen sowie anderer Machine Learning Algorithmen. Während Deep Learning perfekt zur Untersuchung komplexer Daten wie Bild- und Audiodaten passt, wird es zunehmend auch für Use Cases benutzt, für die andere Frameworks besser geeignet sind. Bild 6 zeigt eine kompakte Entscheidungsmatrix [10] für die derzeit verbreitetsten ML-Frameworks und adressiert häufige Praxisprobleme: Entweder werden Algorithmen benutzt, die für den Use Case nicht oder kaum geeignet sind oder das gewählte Framework kann die aufkommenden Datenmengen nicht bewältigen. Die Unterteilung der Frameworks in Small Data, Big Data und Complex Data ist etwas plakativ, soll aber bei der Auswahl der Frameworks nach Art und Volumen der Daten helfen. Die Grenze zwischen Big Data zu Small Data ist dabei dort zu ziehen, wo die Datenmengen so groß sind, dass sie nicht mehr auf einem einzelnen Computer, sondern in einem verteilten Cluster ausgewertet werden müssen. Complex Data steht in dieser Matrix für unstrukturierte Daten wie Bild- und Audiodateien, für die sich Deep Learning Frameworks sehr gut eignen.

Abbildung 6: Entscheidungsmatrix zu aktuell verbreiteten Machine Learning Frameworks

## Self-Service Machine Learning in Business Intelligence-Tools

Mit einfach zu bedienenden Business Intelligence-Werkzeugen zur Datenvisualisierung ist es für Analytiker und für weniger technisch versierte Anwender recht einfach, komplexe Daten aussagekräftig in interaktiven Dashboards zu präsentieren. Hersteller wie Tableau, Qlik und Oracle spielen ihre Stärken insbesondere im Bereich Visual Analytics aus. Statt statische Berichte oder Excel-Dateien vor dem nächsten Meeting zu verschicken, erlauben moderne Besprechungs- und Kreativräume interaktive Datenanalysen am Smartboard inklusive Änderung der Abfragefilter, Perspektivwechsel und Drill-downs. Im Rahmen von Data Science-Projekten können diese Werkzeuge sowohl zur Exploration von Daten als auch zur Visualisierung der Ergebnisse komplexer Machine Learning-Modelle sinnvoll eingesetzt werden. Prognosen, Scores und weiterer ML-Modell-Output lässt sich so schneller verstehen und unterstützt die Entscheidungsfindung bzw. Ableitung der nächsten Maßnahmen für den Geschäftsprozess. Im Rahmen einer IT-Gesamtarchitektur sind Analyse-Notebooks und Datenvisualisierungswerkzeuge für die Standard-Analytics-Toolbox Unternehmens gesetzt. Mit Hinblick auf effiziente Team-Zusammenarbeit, unternehmensinternen Austausch und Kommunikation von Ergebnissen sollte aber nicht nur auf reine Desktop-Werkzeuge gesetzt, sondern Server-Lösungen betrachtet und zusammen mit einem Nutzerkonzept eingeführt werden, um zehnfache Report-Dubletten, konkurrierende Statistiken („MS Excel Hell“) einzudämmen.

Abbildung 7: Datenexploration in Tableau – leicht gemacht für Fachanwender und Data Scientists

Zusätzliche Statistikfunktionen bis hin zur Möglichkeit R- und Python-Code bei der Analyse auszuführen, öffnet auch Fachanwender die Tür zur Welt des Maschinellen Lernens. Bild 7 zeigt das Werkzeug Tableau Desktop mit der Analyse kalifornischer Hauspreise (demselben Datensatz wie oben im Jupyter Notebook-Abschnitt wie in Bild 4) und einer Heatmap-Visualisierung zur Hervorhebung der teuersten Wohnlagen. Mit wenigen Klicks ist auch der Einsatz deskriptiver Statistik möglich, mit der sich neben Lagemaßen (Median, Quartilswerte) auch Streuungsmaße (Spannweite, Interquartilsabstand) sowie die Form der Verteilung direkt aus dem Box-Plot in Bild 7 ablesen und sogar über das Vorhandensein von Ausreißern im Datensatz eine Feststellung treffen lassen. Vorteil dieser Visualisierungen sind ihre hohe Informationsdichte, die allerdings vom Anwender auch richtig interpretiert werden muss. Bei der Beurteilung der Attribute, mit ihren Wertausprägungen und Abhängigkeiten innerhalb des Data Sets, benötigen Citizen Data Scientists (eine Wortschöpfung von Gartner) allerdings dann doch die mathematischen bzw. statistischen Grundlagen, um Falschinterpretationen zu vermeiden. Fraglich ist auch der Nutzen des Data Flow Editors [11] in Oracle Data Visualization, mit dem eins oder mehrere der im Werkzeug integrierten Machine Learning-Modelle trainiert und evaluiert werden können: technisch lassen sich Ergebnisse erzielen und anhand einiger Performance-Metriken die Modellgüte auch bewerten bzw. mit anderen Modellen vergleichen – aber wer kann die erzielten Ergebnisse (wissenschaftlich) verteidigen? Gleiches gilt für die Integration vorhandener R- und Python Skripte, die am Ende dann doch eine Einweisung der Anwender bzgl. Parametrisierung der ML-Modelle und Interpretationshilfen bei den erzielten Ergebnissen erfordern.

## Machine Learning in und mit Datenbanken

Die Nutzung eingebetteter 1-click Analytics-Funktionen der oben vorgestellten Data Visualization-Tools ist zweifellos komfortabel und zum schnellen Experimentieren geeignet. Der gegenteilige und eher puristische Ansatz wäre dagegen die Implementierung eigener Machine Learning Modelle in der Datenbank. Für die Umsetzung des gewählten Algorithmus reichen schon vorhandene Bordmittel in der Datenbank aus: SQL inklusive mathematischer und statistische SQL-Funktionen, Tabellen zum Speichern der Ergebnisse bzw. für das ML-Modell-Management und Stored Procedures zur Abbildung komplexer Geschäftslogik und auch zur Ablaufsteuerung. Solange die Algorithmen ausreichend skalierbar sind, gibt es viele gute Gründe, Ihre Data Warehouse Engine für ML einzusetzen:

• Einfachheit – es besteht keine Notwendigkeit, eine andere Compute-Plattform zu managen, zwischen Systemen zu integrieren und Daten zu extrahieren, transferieren, laden, analysieren usw.
• Sicherheit – Die Daten bleiben dort, wo sie gut geschützt sind. Es ist nicht notwendig, Datenbank-Anmeldeinformationen in externen Systemen zu konfigurieren oder sich Gedanken darüber zu machen, wo Datenkopien verteilt sein könnten.
• Performance – Eine gute Data Warehouse Engine verwaltet zur Optimierung von SQL Abfragen viele Metadaten, die auch während des ML-Prozesses wiederverwendet werden könnten – ein Vorteil gegenüber General-purpose Compute Plattformen.

Die Implementierung eines minimalen, aber legitimen ML-Algorithmus wird in [12] am Beispiel eines Entscheidungsbaums (Decision Tree) im Snowflake Data Warehouse gezeigt. Decision Trees kommen für den Aufbau von Regressions- oder Klassifikationsmodellen zum Einsatz, dabei teilt man einen Datensatz in immer kleinere Teilmengen auf, die ihrerseits in einem Baum organisiert sind. Bild 8 zeigt die Snowflake Benutzer­oberfläche und ein Ausschnitt von der Stored Procedure, die dynamisch alle SQL-Anweisungen zur Berechnung des Decision Trees nach dem ID3 Algorithmus [13] generiert.

Abbildung 8: Snowflake SQL-Editor mit Stored Procedure zur Berechnung eines Decission Trees

Allerdings ist der Entwicklungs- und Implementierungsprozess für ein Machine Learning Modell umfassender: Es sind relevante Daten zu identifizieren und für das ML-Modell vorzubereiten. Einfach Rohdaten bzw. nicht aggregierten Informationen aus Datenbanktabellen zu extrahieren reicht nicht aus, stattdessen benötigt ein ML-Modell als Input eine flache, meist sehr breite Tabelle mit vielen Aggregaten, die als Features bezeichnet werden. Erst dann kann der Prozess fortgesetzt und der für die Aufgabenstellung ausgewählte Algorithmus trainiert und die Modellgüte bewertet werden. Ist das Ergebnis zufriedenstellend, steht die Implementierung des ML-Modells in der Zielumgebung an und muss sich künftig beim Scoring „frischer Datensätze“ bewähren. Viele zeitaufwändige Teilaufgaben also, bei der zumindest eine Teilautomatisierung wünschenswert wäre. Allein die Datenaufbereitung kann schon bis zu 70…80% der gesamten Projektzeit beanspruchen. Und auch die Implementierung eines ML-Modells wird häufig unterschätzt, da in Produktionsumgebungen der unterstützte Technologie-Stack definiert und ggf. für Machine Learning-Aufgaben erweitert werden muss. Daher ist es reizvoll, wenn das Datenbankmanagement-System auch hier einsetzbar ist – sofern die geforderten Algorithmen dort abbildbar sind. Wie ein ML-Modell für die Kundenabwanderungsprognose (Churn Prediction) werkzeuggestützt mit Xpanse AI entwickelt und beschleunigt im Snowflake Cloud Data Warehouse bereitgestellt werden kann, beschreibt [14] sehr anschaulich: Die benötigten Datenextrakte sind schnell aus Snowflake entladen und stellen den Input für ein neues Xpanse AI-Projekt dar. Sobald notwendige Tabellenverknüpfungen und andere fachliche Informationen hinterlegt sind, analysiert das Tool Datenstrukturen und transformiert alle Eingangstabellen in eine flache Zwischentabelle (u.U. mit Hunderten von Spalten), auf deren Basis im Anschluss ML-Modelle trainiert werden. Nach dem ML-Modell-Training erfolgt die Begutachtung der Ergebnisse: das erstellte Dataset, Güte des ML-Modells und der generierte SQL(!) ETL-Code zur Erstellung der Zwischentabelle sowie die SQL-Repräsentation des ML-Modells, das basierend auf den Input-Daten Wahrscheinlichkeitswerte berechnet und in einer Scoring-Tabelle ablegt. Die Vorteile dieses Ansatzes sind liegen auf der Hand: kürzere Projektzeiten, der Einsatz im Rahmen des Snowflake Cloud Data Warehouse, macht das Experimentieren mit der Zuweisung dedizierter Compute-Ressourcen für die performante Verarbeitung äußerst einfach. Grenzen liegen wiederum bei der zur Verfügung stehenden Algorithmen.

## Spezialisierte Software Suites für Machine Learning

Während sich im Markt etablierte Business Intelligence- und Datenintegrationswerkzeuge mit Erweiterungen zur Ausführung von Python- und R-Code als notwendigen Bestandteil der Analyse-Toolbox für den Data Science Prozess positionieren, gibt es daneben auch Machine-Learning-Plattformen, die auf die Arbeit mit künstlicher Intelligenz (KI) zugeschnittenen sind. Für den Einstieg in Data Science bieten sich die oft vorhandenen quelloffenen Distributionen an, die auch über Enterprise-Versionen mit erweiterten Möglichkeiten für beschleunigtes maschinelles Lernen durch Einsatz von Grafikprozessoren (GPUs), bessere Skalierung sowie Funktionen für das ML-Modell Management (z.B. durch Versionsmanagement und Automatisierung) verfügen.

Eine beliebte Machine Learning-Suite ist das Open Source Projekt H2O. Die Lösung des gleichnamigen kalifornischen Unternehmens verfügt über eine R-Schnittstelle und ermöglicht Anwendern dieser statistischen Programmiersprache Vorteile in puncto Performance. Die in H2O verfügbaren Funktionen und Algorithmen sind optimiert und damit eine gute Alternative für das bereits standardmäßig in den R-Paketen verfügbare Funktionsset. H2O implementiert Algorithmen aus dem Bereich Statistik, Data-Mining und Machine Learning (generalisierte Lineare Modelle, K-Means, Random Forest, Gradient Boosting und Deep Learning) und bietet mit einer In-Memory-Architektur und durch standardmäßige Parallelisierung über alle vorhandenen Prozessorkerne eine gute Basis, um komplexe Machine-Learning-Modelle schneller trainieren zu können. Bild 9 zeigt wieder anhand des Datensatzes zur Analyse der kalifornischen Hauspreise die webbasierte Benutzeroberfläche H20 Flow, die den oben beschriebenen Juypter Notebook-Ansatz mit zusätzlich integrierter Benutzerführung für die wichtigsten Prozessschritte eines Machine-Learning-Projektes kombiniert. Mit einigen Klicks kann das California Housing Dataset importiert, in einen H2O-spezifischen Dataframe umgewandelt und anschließend in Trainings- und Testdatensets aufgeteilt werden. Auswahl, Konfiguration und Training der Machine Learning-Modelle erfolgt entweder durch den Anwender im Einsteiger-, Fortgeschrittenen- oder Expertenmodus bzw. im Auto-ML-Modus. Daran anschließend erlaubt H20 Flow die Vorhersage für die Zielvariable (im Beispiel: Hauspreis) für noch unbekannte Datensätze und die Aufbereitung der Ergebnismenge. Welche Unterstützung H2O zur Produktivsetzung von ML-Modellen anbietet, wird an einem Beispiel in den folgenden Abschnitten betrachtet.

Abbildung 9: H2O Flow Benutzeroberfläche – Datenaufbereitung, ML-Modell-Training und Evaluierung.

## Vom Prototyp zur produktiven Machine Learning-Lösung

Warum ist es für viele Unternehmen noch schwer, einen Nutzen aus ihren ersten Data Science-Aktivitäten, Data Labs etc. zu ziehen? In der Praxis zeigt sich, erst durch Operationalisierung von Machine Learning-Resultaten in der Produktionsumgebung entsteht echter Geschäftswert und nur im Tagesgeschäft helfen robuste ML-Modelle mit hoher Güte bei der Erreichung der gesteckten Unternehmensziele. Doch leider erweist sich der Weg vom Prototypen bis hin zum Produktiveinsatz bei vielen Initativen noch als schwierig. Bild 10 veranschaulicht ein typisches Szenario: Data Science-Teams fällt es in ihrer Data Lab-Umgebung technisch noch leicht, Prototypen leistungsstarker ML-Modelle mit Hilfe aktueller ML-Frameworks wie TensorFlow-, Keras- und Word2Vec auf ihren Laptops oder in einer Sandbox-Umgebung zu erstellen. Doch je nach verfügbarer Infrastruktur kann, wegen Begrenzungen bei Rechenleistung oder Hauptspeicher, nur ein Subset der Produktionsdaten zum Trainieren von ML-Modellen herangezogen werden. Ergebnispräsentationen an die Stakeholder der Data Science-Projekte erfolgen dann eher durch Storytelling in MS Powerpoint bzw. anhand eines Demonstrators – selten aber technisch schon so umgesetzt, dass anderere Applikationen z.B. über eine REST-API von dem neuen Risiko Scoring-, dem Bildanalyse-Modul etc. (testweise) Gebrauch machen können. Ausgestattet mit einer Genehmigung vom Management, übergibt das Data Science-Team ein (trainiertes) ML-Modell an das Software Engineering-Team. Nach der Übergabe muss sich allerdings das Engineering-Team darum kümmern, dass das ML-Modell in eine für den Produktionsbetrieb akzeptierte Programmiersprache, z.B. in Java, neu implementiert werden muss, um dem IT-Unternehmensstandard (siehe Line of Governance in Bild 10) bzw. Anforderungen an Skalierbarkeit und Laufzeitverhalten zu genügen. Manchmal sind bei einem solchen Extraschritt Abweichungen beim ML-Modell-Output und in jedem Fall signifikante Zeitverluste beim Deployment zu befürchten.

Abbildung 10: Übergabe von Machine Learning-Resultaten zur Produktivsetzung im Echtbetrieb

Unterstützt das Data Science-Team aktiv bei dem Deployment, dann wäre die Einbettung des neu entwickelten ML-Modells in eine Web-Applikation eine beliebte Variante, bei der typischerweise Flask, Tornado (beides Micro-Frameworks für Python) und Shiny (ein auf R basierendes HTML5/CSS/JavaScript Framework) als Technologiekomponenten zum Zuge kommen. Bei diesem Vorgehen müssen ML-Modell, Daten und verwendete ML-Pakete/Abhängigkeiten in einem Format verpackt werden, das sowohl in der Data Science Sandbox als auch auf Produktionsservern lauffähig ist. Für große Unternehmen kann dies einen langwierigen, komplexen Softwareauslieferungsprozess bedeuten, der ggf. erst noch zu etablieren ist. In dem Zusammenhang stellt sich die Frage, wie weit die Erfahrung des Data Science-Teams bei der Entwicklung von Webanwendungen reicht und Aspekte wie Loadbalancing und Netzwerkverkehr ausreichend berücksichtigt? Container-Virtualisierung, z.B. mit Docker, zur Isolierung einzelner Anwendungen und elastische Cloud-Lösungen, die on-Demand benötigte Rechenleistung bereitstellen, können hier Abhilfe schaffen und Teil der Lösungsarchitektur sein. Je nach analytischer Aufgabenstellung ist das passende technische Design [15] zu wählen: Soll das ML-Modell im Batch- oder Near Realtime-Modus arbeiten? Ist ein Caching für wiederkehrende Modell-Anfragen vorzusehen? Wie wird das Modell-Deployment umgesetzt, In-Memory, Code-unabhängig durch Austauschformate wie PMML, serialisiert via R- oder Python-Objekte (Pickle) oder durch generierten Code? Zusätzlich muss für den Produktiveinsatz von ML-Modellen auch an unterstützenden Konzepten zur Bereitstellung, Routing, Versions­management und Betrieb im industriellen Maßstab gearbeitet werden, damit zuverlässige Machine Learning-Produkte bzw. -Services zur internen und externen Nutzung entstehen können (siehe dazu Bild 11)

Abbildung 11: Unterstützende Funktionen für produktive Machine Learning-Lösungen

Die Deployment-Variante „Machine Learning Code-Generierung“ lässt sich gut an dem bereits mit H2O Flow besprochenen Beispiel veranschaulichen. Während Bild 9 hierzu die Schritte für Modellaufbau, -training und -test illustriert, zeigt Bild 12 den Download-Vorgang für den zuvor generierten Java-Code zum Aufbau eines ML-Modells zur Vorhersage kalifornischer Hauspreise. In dem generierten Java-Code sind die in H2O Flow vorgenommene Datenaufbereitung sowie alle Konfigurationen für den Gradient Boosting Machine (GBM)-Algorithmus gut nachvollziehbar, Bild 13 gibt mit den ersten Programmzeilen einen ersten Eindruck dazu und erinnert gleichzeitig an den ähnlichen Ansatz der oben mit dem Snowflake Cloud Data Warehouse und dem Tool Xpanse AI bereits beschrieben wurde.

Abbildung 12: H2O Flow Benutzeroberfläche – Java-Code Generierung und Download eines trainierten Models

Abbildung 13: Generierter Java-Code eines Gradient Boosted Machine – Modells zur Vorhersage kaliforn. Hauspreise

Nach Abschluss der Machine Learning-Entwicklung kann der Java-Code des neuen ML-Modells, z.B. unter Verwendung der Apache Kafka Streams API, zu einer Streaming-Applikation hinzugefügt und publiziert werden [16]. Vorteil dabei: Die Kafka Streams-Applikation ist selbst eine Java-Applikation, in die der generierte Code des ML-Modells eingebettet werden kann (siehe Bild 14). Alle zukünftigen Events, die neue Immobilien-Datensätze zu Häusern aus Kalifornien mit (denselben) Features wie Geoposition, Alter des Gebäudes, Anzahl Zimmer etc. enthalten und als ML-Modell-Input über Kafka Streams hereinkommen, werden mit einer Vorhersage des voraussichtlichen Gebäudepreises von dem auf historischen Daten trainierten ML-Algorithmus beantwortet. Ein Vorteil dabei: Weil die Kafka Streams-Applikation unter der Haube alle Funktionen von Apache Kafka nutzt, ist diese neue Anwendung bereits für den skalierbaren und geschäftskritischen Einsatz ausgelegt.

Abbildung 14: Deployment des generierten Java-Codes eines H2O ML-Models in einer Kafka Streams-Applikation

## Machine Learning as a Service – “API-first” Ansatz

In den vorherigen Abschnitten kam bereits die Herausforderung zur Sprache, wenn es um die Überführung der Ergebnisse eines Datenexperiments in eine Produktivumgebung geht. Während die Mehrheit der Mitglieder eines Data Science Teams bevorzugt R, Python (und vermehrt Julia) als Programmiersprache einsetzen, gibt es auf der Abnehmerseite das Team der Softwareingenieure, die für technische Implementierungen in der Produktionsumgebung zuständig sind, womöglich einen völlig anderen Technologie-Stack verwenden (müssen). Im Extremfall droht das Neuimplementieren eines Machine Learning-Modells, im besseren Fall kann Code oder die ML-Modellspezifikation transferiert und mit wenig Aufwand eingebettet (vgl. das Beispiel H2O und Apache Kafka Streams Applikation) bzw. direkt in einer neuen Laufzeitumgebung ausführbar gemacht werden. Alternativ wählt man einen „API-first“-Ansatz und entkoppelt das Zusammenwirken von unterschiedlich implementierten Applikationen bzw. -Applikationsteilen via Web-API’s. Data Science-Teams machen hierzu z.B. die URL Endpunkte ihrer testbereiten Algorithmen bekannt, die von anderen Softwareentwicklern für eigene „smarte“ Applikationen konsumiert werden. Durch den Aufbau von REST-API‘s kann das Data Science-Team den Code ihrer ML-Modelle getrennt von den anderen Teams weiterentwickeln und damit eine Arbeitsteilung mit klaren Verantwortlichkeiten herbeiführen, ohne Teamkollegen, die nicht am Machine Learning-Aspekt des eines Projekts beteiligt sind, bei ihrer Arbeit zu blockieren.

Bild 15 zeigt ein einfaches Szenario, bei dem die Gegenstandserkennung von beliebigen Bildern mit einem Deep Learning-Verfahren umgesetzt ist. Einzelne Fotos können dabei via Kommandozeileneditor als Input für die Bildanalyse an ein vortrainiertes Machine Learning-Modell übermittelt werden. Die Information zu den erkannten Gegenständen inkl. Wahrscheinlichkeitswerten kommt dafür im Gegenzug als JSON-Ausgabe zurück. Für die Umsetzung dieses Beispiels wurde in Python auf Basis der Open Source Deep-Learning-Bibliothek Keras, ein vortrainiertes ML-Modell mit Hilfe des Micro Webframeworks Flask über eine REST-API aufrufbar gemacht. Die in [17] beschriebene Applikation kümmert sich außerdem darum, dass beliebige Bilder via cURL geladen, vorverarbeitet (ggf. Wandlung in RGB, Standardisierung der Bildgröße auf 224 x 224 Pixel) und dann zur Klassifizierung der darauf abgebildeten Gegenstände an das ML-Modell übergeben wird. Das ML-Modell selbst verwendet eine sog. ResNet50-Architektur (die Abkürzung steht für 50 Layer Residual Network) und wurde auf Grundlage der öffentlichen ImageNet Bilddatenbank [18] vortrainiert. Zu dem ML-Modell-Input (in Bild 15: Fußballspieler in Aktion) meldet das System für den Tester nachvollziehbare Gegenstände wie Fußball, Volleyball und Trikot zurück, fragliche Klassifikationen sind dagegen Taschenlampe (Torch) und Schubkarre (Barrow).

Abbildung 15: Gegenstandserkennung mit Machine Learning und vorgegebenen Bildern via REST-Service

Bei Aufbau und Bereitstellung von Machine Learning-Funktionen mittels REST-API’s bedenken IT-Architekten und beteiligte Teams, ob der Einsatzzweck eher Rapid Prototyping ist oder eine weitreichende Nutzung unterstützt werden muss. Während das oben beschriebene Szenario mit Python, Keras und Flask auf einem Laptop realisierbar ist, benötigen skalierbare Deep Learning Lösungen mehr Aufmerksamkeit hinsichtlich der Deployment-Architektur [19], in dem zusätzlich ein Message Broker mit In-Memory Datastore eingehende bzw. zu analysierende Bilder puffert und dann erst zur Batch-Verarbeitung weiterleitet usw. Der Einsatz eines vorgeschalteten Webservers, Load Balancers, Verwendung von Grafikprozessoren (GPUs) sind weitere denkbare Komponenten für eine produktive ML-Architektur.

Als abschließendes Beispiel für einen leistungsstarken (und kostenpflichtigen) Machine Learning Service soll die Bildanalyse von Google Cloud Vision [20] dienen. Stellt man dasselbe Bild mit der Fußballspielszene von Bild 15 und Bild 16 bereit, so erkennt der Google ML-Service neben den Gegenständen weit mehr Informationen: Kontext (Teamsport, Bundesliga), anhand der Gesichtserkennung den Spieler selbst  und aktuelle bzw. vorherige Mannschaftszugehörigkeiten usw. Damit zeigt sich am Beispiel des Tech-Giganten auch ganz klar: Es kommt vorallem auf die verfügbaren Trainingsdaten an, inwieweit dann mit Algorithmen und einer dazu passenden Automatisierung (neue) Erkenntnisse ohne langwierigen und teuren manuellen Aufwand gewinnen kann. Einige Unternehmen werden feststellen, dass ihr eigener – vielleicht einzigartige – Datenschatz einen echten monetären Wert hat?

Abbildung 16: Machine Learning Bezahlprodukt (Google Vision)

## Fazit

Machine Learning ist eine interessante “Challenge” für Architekten. Folgende Punkte sollte man bei künftigen Initativen berücksichtigen:

• Finden Sie das richtige Geschäftsproblem bzw geeignete Use Cases
• Identifizieren und definieren Sie die Einschränkungen (Sind z.B. genug Daten vorhanden?) für die zu lösende Aufgabenstellung
• Nehmen Sie sich Zeit für das Design von Komponenten und Schnittstellen
• Berücksichtigen Sie frühzeitig mögliche organisatorische Gegebenheiten und Einschränkungen
• Denken Sie nicht erst zum Schluss an die Produktivsetzung Ihrer analytischen Modelle oder Machine Learning-Produkte
• Der Prozess ist insgesamt eine Menge Arbeit, aber es ist keine Raketenwissenschaft.

## Visual Question Answering with Keras – Part 1

This is Part I of II of the Article Series Visual Question Answering with Keras

Making Computers Intelligent to answer from images

If we look closer in the history of Artificial Intelligence (AI), the Deep Learning has gained more popularity in the recent years and has achieved the human-level performance in the tasks such as Speech Recognition, Image Classification, Object Detection, Machine Translation and so on. However, as humans, not only we but also a five-year child can normally perform these tasks without much inconvenience. But the development of such systems with these capabilities has always considered an ambitious goal for the researchers as well as for developers.

In this series of blog posts, I will cover an introduction to something called VQA (Visual Question Answering), its available datasets, the Neural Network approach for VQA and its implementation in Keras and the applications of this challenging problem in real life.

1 Introduction

2 What is exactly Visual Question Answering?

3 Prerequisites

4 Datasets available for VQA

4.1 DAQUAR Dataset

4.2 CLEVR Dataset

4.3 FigureQA Dataset

4.4 VQA Dataset

5 Real-life applications of VQA

6 Conclusion

1. Introduction:

Let’s say you are given a below picture along with one question. Can you answer it?

I expect confidently you all say it is the Kitchen without much inconvenience which is also the right answer. Even a five-year child who just started to learn things might answer this question correctly.

Alright, but can you write a computer program for such type of task that takes image and question about the image as an input and gives us answer as output?

Before the development of the Deep Neural Network, this problem was considered as one of the difficult, inconceivable and challenging problem for the AI researcher’s community. However, due to the recent advancement of Deep Learning the systems are capable of answering these questions with the promising result if we have a required dataset.

Now I hope you have got at least some intuition of a problem that we are going to discuss in this series of blog posts. Let’s try to formalize the problem in the below section.

1. What is exactly Visual Question Answering?:

We can define, “Visual Question Answering(VQA) is a system that takes an image and natural language question about the image as an input and generates natural language answer as an output.”

VQA is a research area that requires an understanding of vision(Computer Vision)  as well as text(NLP). The main beauty of VQA is that the reasoning part is performed in the context of the image. So if we have an image with the corresponding question then the system must able to understand the image well in order to generate an appropriate answer. For example, if the question is the number of persons then the system must able to detect faces of the persons. To answer the color of the horse the system need to detect the objects in the image. Many of these common problems such as face detection, object detection, binary object classification(yes or no), etc. have been solved in the field of Computer Vision with good results.

To summarize a good VQA system must be able to address the typical problems of CV as well as NLP.

To get a better feel of VQA you can try online VQA demo by CloudCV. You just go to this link and try uploading the picture you want and ask the related question to the picture, the system will generate the answer to it.

1. Prerequisites:

In the next post, I will walk you through the code for this problem using Keras. So I assume that you are familiar with:

1. Fundamental concepts of Machine Learning
2. Multi-Layered Perceptron
3. Convolutional Neural Network
4. Recurrent Neural Network (especially LSTM)
6. Transfer Learning
7. Hyperparameter Optimization
8. Python and Keras syntax
1. Datasets available for VQA:

As you know problems related to the CV or NLP the availability of the dataset is the key to solve the problem. The complex problems like VQA, the dataset must cover all possibilities of questions answers in real-world scenarios. In this section, I will cover some of the datasets available for VQA.

4.1 DAQUAR Dataset:

The DAQUAR dataset is the first dataset for VQA that contains only indoor scenes. It shows the accuracy of 50.2% on the human baseline. It contains images from the NYU_Depth dataset.

Example of DAQUAR dataset

The main disadvantage of DAQUAR is the size of the dataset is very small to capture all possible indoor scenes.

4.2 CLEVR Dataset:

The CLEVR Dataset from Stanford contains the questions about the object of a different type, colors, shapes, sizes, and material.

It has

• A training set of 70,000 images and 699,989 questions
• A validation set of 15,000 images and 149,991 questions
• A test set of 15,000 images and 14,988 questions

Image Source: https://cs.stanford.edu/people/jcjohns/clevr/?source=post_page

4.3 FigureQA Dataset:

FigureQA Dataset contains questions about the bar graphs, line plots, and pie charts. It has 1,327,368 questions for 100,000 images in the training set.

4.4 VQA Dataset:

As comapred to all datasets that we have seen so far VQA dataset is relatively larger. The VQA dataset contains open ended as well as multiple choice questions. VQA v2 dataset contains:

• 82,783 training images from COCO (common objects in context) dataset
• 40, 504 validation images and 81,434 validation images
• 443,757 question-answer pairs for training images
• 214,354 question-answer pairs for validation images.

As you might expect this dataset is very huge and contains 12.6 GB of training images only. I have used this dataset in the next post but a very small subset of it.

This dataset also contains abstract cartoon images. Each image has 3 questions and each question has 10 multiple choice answers.

1. Real-life applications of VQA:

There are many applications of VQA. One of the famous applications is to help visually impaired people and blind peoples. In 2016, Microsoft has released the “Seeing AI” app for visually impaired people to describe the surrounding environment around them. You can watch this video for the prototype of the Seeing AI app.

Another application could be on social media or e-commerce sites. VQA can be also used for educational purposes.

1. Conclusion:

I hope this explanation will give you a good idea of Visual Question Answering. In the next blog post, I will walk you through the code in Keras.

If you like my explanations, do provide some feedback, comments, etc. and stay tuned for the next post.

## Understanding Dropout and implementing it on MNIST dataset

Over-fitting is a major problem in deep learning and a plethora of techniques have been introduced to prevent it. One of the most effective one is called “dropout”.  Let’s use the analogy of a person going to gym for understanding this. Let’s say the person going to gym mostly uses his dominant arm, say his right arm to pick up weights. After some time, he notices that his dominant arm is developing a large muscle, but not the other arm. So, what can he do? Obviously, he needs to involve both his arms while training. Sometimes he should stop using his right arm, and use the left arm to lift weights and vice versa.

Something like this happens commonly in neural networks. Sometime one part of the network has very large weights and ends up dominating the training. While other part of the network remains weak and does not really play a role in the training. So, what dropout does to solve this problem, is it randomly shuts off some nodes and stop the gradients flowing through it. So, our forward and back propagation happen without those nodes. In that case the rest of the nodes need to pick up the slack and be more active in the training. We define a probability of the nodes getting dropped. For example, P=0.5 means there is a 50% chance a node will be dropped.

Figure 1 demonstrates the dropout technique, taken from the original research paper.

Our network can never rely on any given node because it can be squashed at any given time. Hence the network is forced to learn redundant representation for everything to make sure at least some of the information remains. Redundant representation leads our network to be more robust. It also acts as ensemble of many networks, since at every epoch random nodes are dropped, each time our network will be different. Ensemble of different networks perform better than a single network since they capture more randomness. Please note, only non-output nodes are dropped.

Let’s, look at the python code to implement dropout in a neural network:

## 1. Einleitung und Inhalt

Früher oder später wird jede Person, welche sich mit den Themen Daten, KI, Machine Learning und Deep Learning auseinander setzt, mit TensorFlow in Kontakt geraten. Für diejenigen wird der Zeitpunkt kommen, an dem sie sich damit befassen möchten/müssen/wollen.

Und genau für euch ist diese Artikelserie ausgelegt. Gemeinsam wollen wir die ersten Schritte in die Welt von Deep Learning und neuronalen Netzen mit TensorFlow wagen und unsere eigenen Beispiele realisieren. Dabei möchten wir uns auf das Wesentlichste konzentrieren und die Thematik Schritt für Schritt in 4 Artikeln angehen, welche wie folgt aufgebaut sind:

Wenn ihr die Praxisbeispiele in den Artikeln 3 & 4 aktiv mit bestreiten wollt, dann ist es vorteilhaft, wenn ihr bereits mit Python gearbeitet habt und die Grundlagen dieser Programmiersprache beherrscht. Jedoch werden alle Handlungen und alle Zeilen sehr genau kommentiert, so dass es leicht verständlich bleibt.

Neben den Programmierfähigkeiten ist es hilfreich, wenn ihr euch mit der Funktionsweise von neuronalen Netzen auskennt, da wir im späteren Verlauf diese modellieren wollen. Jedoch gehen wir vor der Programmierung  kurz auf die Theorie ein und werden das Wichtigste nochmal erwähnen.

Zu guter Letzt benötigen wir für unseren Theorie-Teil ein Mindestmaß an Mathematik um die Grundlagen der neuronalen Netze zu verstehen. Aber auch hier sind die Anforderungen nicht hoch und wir sind vollkommen gut  damit bedient, wenn wir unser Wissen aus dem Abitur noch nicht ganz vergessen haben.

## 2. Ziele dieser Artikelserie

Diese Artikelserie ist speziell an Personen gerichtet, welche einen ersten Schritt in die große und interessante Welt von Deep Learning wagen möchten, die am Anfang nicht mit zu vielen Details überschüttet werden wollen und lieber an kleine und verdaulichen Häppchen testen wollen, ob dies das Richtige für sie ist. Unser Ziel wird sein, dass wir ein Grundverständnis für TensorFlow entwickeln und die Grundlagen zur Nutzung beherrschen, um mit diesen erste Modelle zu erstellen.

## 3. Was ist TensorFlow?

Viele von euch haben bestimmt von TensorFlow in Verbindung mit Deep Learning bzw. neuronalen Netzen gehört. Allgemein betrachtet ist TensorFlow ein Software-Framework zur numerischen Berechnung von Datenflussgraphen mit dem Fokus maschinelle Lernalgorithmen zu beschreiben. Kurz gesagt: Es ist ein Tool um Deep Learning Modelle zu realisieren.

Zusatz: Python ist eine Programmiersprache in der wir viele Paradigmen (objektorientiert, funktional, etc.) verwenden können. Viele Tutorials im Bereich Data Science nutzen das imperative Paradigma; wir befehlen Python also Was gemacht und Wie es ausgeführt werden soll. TensorFlow ist dahingehend anders, da es eine datenstrom-orientierte Programmierung nutzt. In dieser Form der Programmierung wird ein Datenfluss-Berechnungsgraph (kurz: Datenflussgraph) erzeugt, welcher durch die Zusammensetzung von Kanten und Knoten charakterisiert wird. Die Kanten enthalten Daten und können diese an Knoten weiterleiten. In den Knoten werden Operationen wie z. B. Addition, Multiplikation oder auch verschiedenste Variationen von Funktionen ausgeführt. Bekannte Programme mit datenstrom-orientierten Paradigmen sind Simulink, LabView oder Knime.

Für das Verständnis von TensorFlow verrät uns der Name bereits erste Informationen über die Funktionsweise. In neuronalen Netzen bzw. in Deep-Learning-Netzen können Eingangssignale, Gewichte oder Bias verschiedene Erscheinungsformen haben; von Skalaren, zweidimensionalen Tabellen bis hin zu mehrdimensionalen Matrizen kann alles dabei sein. Diese Erscheinungsformen werden in Deep-Learning-Anwendungen allgemein als Tensoren bezeichnet, welche durch ein Datenflussgraph ‘fließen’. [1]

## 4. Warum TensorFlow?

Wer in die Welt der KI einsteigen und Deep Learning lernen will, hat heutzutage die Qual der Wahl. Neben TensorFlow gibt es eine Vielzahl von Alternativen wie Keras, Theano, Pytorch, Torch, Caffe, Caffe2, Mxnet und vielen anderen. Warum also TensorFlow?

Das wohl wichtigste Argument besteht darin, dass TensorFlow eine der besten Dokumentationen hat. Google – Herausgeber von TensorFlow – hat TensorFlow stets mit neuen Updates beliefert. Sicherlich aus genau diesen Gründen ist es das meistgenutzte Framework. Zumindest erscheint es so, wenn wir die Stars&Forks auf Github betrachten. [3] Das hat zur Folge, dass neben der offiziellen Dokumentation auch viele Tutorials und Bücher existieren, was die Doku nur noch besser macht.

Natürlich haben alle Frameworks ihre Vor- und Nachteile. Gerade Pytorch von Facebook erfreut sich derzeit großer Beliebtheit, da die Berechnungsgraphen dynamischer Natur sind und damit einige Vorteile gegenüber TensorFlow aufweisen.[2] Auch Keras wäre für den Einstieg eine gute Alternative, da diese Bibliothek großen Wert auf eine einsteiger- und nutzerfreundliche Handhabung legt. Keras kann man sich als eine Art Bedienoberfläche über unsere Frameworks vorstellen, welche vorgefertigte neuronale Netze bereitstellt und uns einen Großteil der Arbeit abnimmt.

Möchte man jedoch ein detailreiches und individuelles Modell bauen und die Theorie dahinter nachvollziehen können, dann ist TensorFlow der beste Einstieg in Deep Learning! Es wird einige Schwierigkeiten bei der Gestaltung unserer Modelle geben, aber durch die gute Dokumentation, der großen Community und der Vielzahl an Beispielen, werden wir gewiss eine Lösung für aufkommende Problemstellungen finden.

## 5. Zusammenfassung und Ausblick

Fassen wir das Ganze nochmal zusammen: TensorFlow ist ein Framework, welches auf der datenstrom-orientierten Programmierung basiert und speziell für die Implementierung von Machine/Deep Learning-Anwendungen ausgelegt ist. Dabei fließen unsere Daten durch eine mehr oder weniger komplexe Anordnung von Berechnungen, welche uns am Ende ein Ergebnis liefert.

Die wichtigsten Argumente zur Wahl von TensorFlow als Einstieg in die Welt des Deep Learnings bestehen darin, dass TensorFlow ausgezeichnet dokumentiert ist, eine große Community besitzt und relativ einfach zu lesen ist. Außerdem hat es eine Schnittstelle zu Python, welches durch die meisten Anwender im Bereich der Datenanalyse bereits genutzt wird.

Wenn ihr es bis hier hin geschafft habt und immer noch motiviert seid den Einstieg mit TensorFlow zu wagen, dann seid gespannt auf den nächsten Artikel. In diesem werden wir dann auf die Funktionsweise von TensorFlow eingehen und einfache Berechnungsgraphen aufbauen, um ein Grundverständnis von TensorFlow zu bekommen. Bleibt also gespannt!

## Quellen

[1] Hope, Tom (2018): Einführung in TensorFlow: DEEP-LEARNING-SYSTEME PROGRAMMIEREN, TRAINIEREN, SKALIEREN UND DEPLOYEN, 1. Auflage

[2] https://www.marutitech.com/top-8-deep-learning-frameworks/