갈루아의 반서재

Telegram bot to monitor and control deep learning experiments


Dependencies

다음의 패키지가 설치되어 있어야 함
  • python-telegram-bot
  • Keras (선택사항, 케라스 콜백 사용시)
  • matplotlib (선택사항, convergence plots 전송시)

다음의 환경에서 테스트함
  • Python 3.6.6
  • Tensorflow 1.12.0
  • Keras 2.2.4
  • Ubuntu 18.04
(tfKeras) founder@hilbert:~/tfKeras/telegrad$ python3 -V
Python 3.6.6
(tfKeras) founder@hilbert:~/tfKeras/telegrad$ python -c 'import keras; print(keras.__version__)'
Using TensorFlow backend.
2.2.4
(tfKeras) founder@hilbert:~/tfKeras/telegrad$ python -c 'import tensorflow as tf; print(tf.__version__)'
1.12.0
(tfKeras) founder@hilbert:~/tfKeras/telegrad$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:        18.04
Codename:       bionic


Installation
python-telegram-bot 을 설치한다.
(tfKeras) founder@hilbert:~$ pip install python-telegram-bot --upgrade
Collecting python-telegram-bot
  Downloading https://files.pythonhosted.org/packages/84/6c/47932a4041ee76650ad1f45a80e1422077e1e99c08a4d7a61cfbe5393d41/python_telegram_bot-11.1.0-py2.py3-none-any.whl (326kB)
    100% |████████████████████████████████| 327kB 21.7MB/s
Requirement already satisfied, skipping upgrade: cryptography in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from python-telegram-bot) (2.3.1)
Requirement already satisfied, skipping upgrade: certifi in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from python-telegram-bot) (2018.11.29)
Collecting future>=0.16.0 (from python-telegram-bot)
  Downloading https://files.pythonhosted.org/packages/90/52/e20466b85000a181e1e144fd8305caf2cf475e2f9674e797b222f8105f5f/future-0.17.1.tar.gz (829kB)
    100% |████████████████████████████████| 829kB 15.7MB/s
Requirement already satisfied, skipping upgrade: idna>=2.1 in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (2.8)
Requirement already satisfied, skipping upgrade: asn1crypto>=0.21.0 in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (0.24.0)
Requirement already satisfied, skipping upgrade: six>=1.4.1 in ./.local/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (1.12.0)
Requirement already satisfied, skipping upgrade: cffi!=1.11.3,>=1.7 in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cryptography->python-telegram-bot) (1.11.5)
Requirement already satisfied, skipping upgrade: pycparser in ./anaconda3/envs/tfKeras/lib/python3.6/site-packages (from cffi!=1.11.3,>=1.7->cryptography->python-telegram-bot) (2.19)
Building wheels for collected packages: future
  Running setup.py bdist_wheel for future ... done
  Stored in directory: /home/founder/.cache/pip/wheels/0c/61/d2/d6b7317325828fbb39ee6ad559dbe4664d0896da4721bf379e
Successfully built future
Installing collected packages: future, python-telegram-bot
Successfully installed future-0.17.1 python-telegram-bot-11.1.0

2. 깃허브 저장소를 복제한다
(tfKeras) founder@hilbert:~/tfKeras$ cd telegrad
(tfKeras) founder@hilbert:~/tfKeras/telegrad$ ls -al
total 88
drwxrwxr-x  3 founder founder  4096 Feb 15 04:00 .
drwxrwxr-x 12 founder founder  4096 Feb 15 03:59 ..
-rw-rw-r--  1 founder founder 35149 Feb 15 04:00 LICENSE
-rw-rw-r--  1 founder founder  6736 Feb 15 04:00 README.md
-rw-rw-r--  1 founder founder 12016 Feb 15 04:00 dl_bot.py
drwxrwxr-x  2 founder founder  4096 Feb 15 04:00 images
-rw-rw-r--  1 founder founder  3521 Feb 15 04:00 keras_mnist_example.py
-rw-rw-r--  1 founder founder  3672 Feb 15 04:00 telegram_bot_callback.py
-rw-rw-r--  1 founder founder 12065 Feb 15 04:00 tf_mnist_example.py

3. dl_bot.py 를 프로젝트에 추가한다. 

4.  (케라스 사용시) telegram_bot_callback.py 프로젝트 추가한다. 

3, 4번 내용은 해당 파일을 쓸 수 있도록 해당 파일을 실행 파일이 위치한 폴더에 위치시키라는 뜻이다.



Usage

Telegram app 을 이용하여 텔레그램 봇을 생성한다. 봇을 생성한 후 그 봇을 찾아서 대화를 시도한다. 여러분과만 통신을 해야하므로 봇에게 여러분의 id 를 알려준다. 아래 링크에 해당 내요이 전부 포함되어 있으니 참고하길 권한다. 

자동으로 해당 봇과 통신하도록 케라스 콜백을 사용할 수도 있고, 또는 커스토마이징을 할 수도 있다. 주의할 점은 일단 여러분이 앱에서 /start 메시지를 보낸 후에 봇은 작동한다는 점이다. 


Keras Callback 
케라스에서 사용하기 위해서는 다음의 블럭의 내용이 필요하다. telegram_token, telegram_user_id 에 해당 내용을 입력하면 된다. 

# Telegram Bot imports
from dl_bot import DLBot
from telegram_bot_callback import TelegramBotCallback

telegram_token = "TOKEN"  # replace TOKEN with your bot's token

#  user id is optional, however highly recommended as it limits the access to you alone.
telegram_user_id = None  # replace None with your telegram user id (integer):

# Create a DLBot instance
bot = DLBot(token=telegram_token, user_id=telegram_user_id)
# Create a TelegramBotCallback instance
telegram_callback = TelegramBotCallback(bot)

keras_mnist_example.py 을 예제로 사용하는 경우 위의 코드로 충분하다. 이 상태로 실행하면 다음과 같다.

먼저 /start 라는 메시지를 전송한다. 사용가능한 명령어들을 보여주게 된다. 

봇은 다음과 같이 훈련 상태를 전송하게 된다.

훈련을 중단할 경우에는 /stoptraining 이라고 입력하면 그만둘지 여부를 다음과 같이 물어오게 된다.


위의 샘플이 아니라 기존 훈련에 적용할려면 다음과 같이 적용할 수 있다. 먼저 위와 마찬가지로 텔레그램 봇을 가져오고, 인스턴스를 생성한 뒤 다음과 같이 telegram_callback 을 model.fit 으로 전달되는 콜백 리스트에 포함시키면 된다. 

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[telegram_callback])

이게 전부다. 실제로 적용해보자. 하단 코드는 다음 코드의 일부다.

2018/12/28 - [딥러닝 Deep Learning] - CNN, 케라스, 텐서플로우 벡엔드를 이용한 이미지 인식 분류기 만들기 Create your first Image Recognition Classifier using CNN, Keras and Tensorflow backend

먼저 텔레그램 봇을 가져온다. token 정보와 사용자 아이디를 수정한 뒤, 콜백 리스트에 telegram_callback 을 추가하고 훈련을 진행한다.

# Telegram Bot imports
from dl_bot import DLBot
from telegram_bot_callback import TelegramBotCallback

telegram_token = "1215646465:DHKDIHGAJGO4G4GD4G46G4"  # replace TOKEN with your bot's token

#  user id is optional, however highly recommended as it limits the access to you alone.
telegram_user_id = 484946464 # replace None with your telegram user id (integer):

# Create a DLBot instance
bot = DLBot(token=telegram_token, user_id=telegram_user_id)
# Create a TelegramBotCallback instance
telegram_callback = TelegramBotCallback(bot)


from IPython.display import display
from PIL import Image

classifier.fit_generator(
        training_set,
        steps_per_epoch = 8000,
        epochs = 20,
        validation_data = test_set,
        validation_steps = 800,
        callbacks = [telegram_callback])

다음과 같이 훈련이 진행되고 있다. 

Epoch 1/20
8000/8000 [==============================] - 4012s 501ms/step - loss: 0.4469 - acc: 0.7836 - val_loss: 0.5881 - val_acc: 0.7722
Send message failed, user did not send /start
Epoch 2/20
8000/8000 [==============================] - 3978s 497ms/step - loss: 0.2619 - acc: 0.8869 - val_loss: 0.8386 - val_acc: 0.7647
Epoch 3/20
8000/8000 [==============================] - 3993s 499ms/step - loss: 0.1642 - acc: 0.9346 - val_loss: 1.0561 - val_acc: 0.7585
Epoch 4/20
5254/8000 [==================>...........] - ETA: 21:45 - loss: 0.1166 - acc: 0.9558


텔레그램을 통해 메시지가 정상적으로 전송되는지 확인해보자.

먼저 /start 메시지를 전송한다.

잠시 후 첫번째 에포크에 대한 정보가 전송된다. /plot 메시지를 통해 그래프로도 확인가능하다. /getlr 은 현재 학습률을 물어보는 명령어이다. /status 메시지를 통해서는 현재 상황을 받아볼 수 있다.

 


참고 https://github.com/eyalzk/telegrad