You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For each input character the `example_batch_predictions` array contains a vector of probabilities of what the next character might be. If probability at position `15` in that vector is, lets say, `0.3` and the probability at position `25` is `1.1` it means that we should better pick the character with the index `25` as next following character.
1359
+
Для каждого символа на входе модели массив `example_batch_predictions` содержит вектор (массив) вероятностей того, какой символ может быть следующим. Если вероятность в позиции `15` этого вектора, пускай, равна `0.3`, а вероятность в позиции `25` равна `1.1` это означает, что стоит выбрать символ с индексом `25` в качестве прогнозируемого (следующего).
1360
1360
1361
-
Since we want our network to generate different recipes (even for the same input), we can't just pick the maximum probability value. In this case we will end up with the same recipe being predicted by the network over and over again. What we will do instead is drawing **samples** from predictions (like the one printed above) by using [tf.random.categorical()](https://www.tensorflow.org/api_docs/python/tf/random/categorical) function. It will bring some fuzziness to the network. For example, let's say we have character `H` as an input, then, by sampling from categorical distribution, our network may predict not only the word `He`, but also words `Hello`, and `Hi` etc.
1361
+
Поскольку мы хотим, чтобы наша модель генерировала разные рецепты (даже при условии одинаковых входных данных), мы не можем всегда выбирать символ с максимальной вероятностью в качестве следующего. Если бы выбирали следующий символ по критерию его максимальной вероятности, то наша модель генерировала бы один и тот же рецепт снова и снова (при одинаковых входных данных). Вместо этого, мы можем попробовать **sampling** по вероятностям с помощью функции [tf.random.categorical()](https://www.tensorflow.org/api_docs/python/tf/random/categorical). Это привнесет своего рода "случайность" или "импровизацию" в предсказания модели. Например, допустим, мы имеем в качестве входа символ `H`. После семплинга, наша сеть может предсказать не только слово `He`, но и слова `Hello`, `Hi` и т.п.
1362
1362
1363
-
### Understanding how `tf.random.categorical` works
1363
+
### Разбираемся, как работает функция `tf.random.categorical()`
1364
+
1365
+
Одним из параметров функции `tf.random.categorical()` является `logits`. Логиты - это матрица размерностью `[batch_size, num_classes]`. Каждый ряд этой матрицы `[i, :]` представляет собой вероятности для каждого класса (в нашем случае дла каждого символа из словаря). В примере ниже вероятность для класса с индексом `0` низкая, но вероятность для класса с индексом `2` - выше. Теперь, предположим, что мы хотим сделать семплинг по этим вероятностям и сгенерировать, пускай, `5` следующих предсказаний. В таком случае вероятности появления каждого класса будут учтены функцией `tf.random.categorical()` и она выдаст нам тензор с 5-ю индексами классов. Мы ожидаем, что класс с индексом `2` будет встречаться чаще остальных.
1364
1366
1365
1367
```python
1366
-
# logits is 2-D Tensor with shape [batch_size, num_classes].
1367
-
# Each slice [i, :] represents the unnormalized log-probabilities for all classes.
1368
-
# In the example below we say that the probability for class "0"
1369
-
# (element with index 0) is low but the probability for class "2" is much higher.
1370
1368
tmp_logits = [
1371
1369
[-0.95, 0, 0.95],
1372
1370
];
1373
1371
1374
-
# Let's generate 5 samples. Each sample is a class index. Class probabilities
1375
-
# are being taken into account (we expect to see more samples of class "2").
As you may see, the model suggests some meaningless predictions, but this is because it wasn't trained yet.
1450
-
1451
-
## Training the model
1452
-
1453
-
We want to train our model to generate recipes as similar to the real ones as possible. We will use all data from dataset for training. There is not need to extract test or validation sub-sets in this case.
1445
+
## Тренируем модель
1454
1446
1455
-
### Attach an optimizer, and a loss function
1447
+
### Оптимизатор и функция потерь
1456
1448
1457
1449
We're going to use [tf.keras.optimizers.Adam](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam) optimizer with [tf.keras.losses.sparse_categorical_crossentropy()](https://www.tensorflow.org/api_docs/python/tf/keras/losses/sparse_categorical_crossentropy) loss function to train the model:
0 commit comments