Instalar o Tensorflow no Raspberry Pi 3

O TensorFlow é uma plataforma de código aberto orientado para implementar soluções de inteligência artificial por aprendizagem (machine learning). O tensorflow possui um ecossistema abrangente e flexível de ferramentas, bibliotecas e recursos da comunidade que permite comunidade desenvolver o estado da arte assim como o desenvolvimento e implementação facilitado de aplicações em machine learning.

A página do tensor flow reúne as principais informações e recursos sobre o tensorflow   e está disponível em:

  • https://www.tensorflow.org/

Outra referência importante é o seguinte repositório:

  • https://github.com/tensorflow/tensorflow

Instalação do tensor flow

A informação para instalação que segui neste documento é a que está disponível no seguinte endereço. A única diferença é que usei o python3 na instalação e faço essa referência aqui.

Como o Raspberry Pi3 não tem uma gráfica com suporte para o CUDA, então a versão a instalar é a CPU-only e pode-se usar os seguintes comandos.

Em python:

Nota: nao consegui colocar o tensorflow a funcionar em python2.7 no raspberry pi3 (apenas funcionou em python3)

pip install tensorflow

Em python3

pip3 install tensorflow

Para instruções mais detalhadas e como instalar a partir das fontes consultar o seguinte link:

https://www.tensorflow.org/install

 

Se este método de instalação não der resultado no Raspberry pi, ver mais abaixo a descrição da minha segunda experiência de instalação do tensorflow que foi bem sucedida.

Primeira experiência de instalação do tensorflow no Raspberry Pi3

O resultado da minha primeira experiência a instalar o tensorflow foi desoladora.

O comando executado:

pip3 install tensorflow

A parte final da saída da sua execução deixando-me optimista sobre o resultado da instalação.

Successfully installed absl-py-0.7.1 astor-0.8.0 enum34-1.1.6 futures-3.1.1 gast-0.2.2 grpcio-1.21.1 h5py-2.9.0 keras-applications-1.0.8 keras-preprocessing-1.1.0 markdown-3.1.1 mock-3.0.5 numpy-1.16.4 protobuf-3.8.0 tensorboard-1.13.1 tensorflow-1.13.1 tensorflow-estimator-1.13.0 termcolor-1.1.0

Seguidamente executei o código de deste indicado.

python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"

/usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: compiletime version 3.4 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.5
return f(*args, **kwds)
/usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: builtins.type size changed, may indicate binary incompatibility. Expected 432, got 412
return f(*args, **kwds)
tf.Tensor(181.6255, shape=(), dtype=float32)

Outro comando de teste (descrito abaixo também me apresentava o erro.

root@dami4:~# python3 -c "import tensorflow as tf; print(tf.GIT_VERSION, tf.VERSION)"
/usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: compiletime version 3.4 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.5
  return f(*args, **kwds)
/usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: builtins.type size changed, may indicate binary incompatibility. Expected 432, got 412
  return f(*args, **kwds)
b'v1.13.0-rc2-5-g6612da8' 1.13.1

Na realidade, olhando bem o erro era mais um warning, no entanto era um mau prenuncio, e eventualmente alguma coisa não estava bem.

Devido a este erro tentei também instalar em python2 com o comando:

pip install tensorflow

No entanto nenhuma das tentativas de execução terminou com sucesso, umas vezes com um erro em que exibia o traceback com as linhas do programa executado:

Downloading https://www.piwheels.org/simple/tensorflow/tensorflow-1.13.1-cp27-none-linux_armv7l.whl (92.5MB)
99% |████████████████████████████████| 92.5MB 4.2MB/s eta 0:00:01Exception:
Traceback (most recent call last):
File “/usr/lib/python2.7/dist-packages/pip/basecommand.py”, line 215, in main

Outras terminava simplesmente assim:

Downloading https://www.piwheels.org/simple/tensorflow/tensorflow-1.13.1-cp27-none-linux_armv7l.whl (92.5MB)
99% |████████████████████████████████| killed

Acabei por desistir e desinstalei a versão do python3 com o seguinte comando:

pip3 uninstall tensorflow

Resolvido a não desistir ainda pensei compilar das fontes, mas resolvi seguir outro caminho.

Segunda experiência de instalação do tensorflow no Raspberry Pi3

Sem ter efectuado uma abordagem mais radical, que seria a instalação das fontes, resolvi procurar por outra fonte de uma pacote de instalação já compilado. Acabei por encontrar o seguinte repositório dedicado ao tensorflow nos ARM:

  • https://github.com/lhelontra/tensorflow-on-arm

Os pacotes do tensorflow pré-compilados alojados no repositório estão disponíveis no seguinte link;

  • https://github.com/lhelontra/tensorflow-on-arm/releases

Tentei instalar primeiro a versão para o python2.7 com o seguinte comando e (mau) resultado:

pip3 install --upgrade https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.13.1/tensorflow-1.13.1-cp27-none-linux_armv7l.whl
tensorflow-1.13.1-cp27-none-linux_armv7l.whl is not a supported wheel on this platform.

Acho que me enganei ao usar o pip3, deveria ser somente pip, para instalar usando o python2. Por isso repeti o comando usando o pip (somente pip).

E voltei a encontrar o erro no download do pacote compilado com um traceback semelhante ao da experiência de instalação anterior.

Passei  à instalação do tensorflow no python3

pip3 install --upgrade https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.13.1/tensorflow-1.13.1-cp35-none-linux_armv7l.whl

A instalação decorreu sem erros e o passei ao teste com o seguinte resultado

root@dami4:~# python3 -c "import tensorflow as tf; print(tf.GIT_VERSION, tf.VERSION)"
b'v1.13.1-1-gabdfa177d6' 1.13.1

O outro teste também executou bem, conforme o comando e resultado abaixo:

python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
tf.Tensor(800.05206, shape=(), dtype=float32)

Pelo que dei por concluida a instalação do tensorflow no python3

Instalação do tensorflow a partir das fontes no raspberry pi

O processo de instalação do tensorflow a partir das fontes no raspberry pi está descrito no seguinte link:

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/makefile#raspberry-pi

Para compilar o tensorflow a partir das fontes é necessário memória. Por isso é necessário preparar um swapfile numa pen USB para que o processo de compilação não termine em erro por falta de memória.

sudo mkswap /dev/XXX

sudo nano /etc/fstab

UUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX none swap sw,pri=5 0 0

sudo swapon -a

A preparação termina com a instalação de uma dependência

apt-get install libatlas-base-dev

Depois da preparação terminar, inicia-se o processo de instalação do tensorflow com:

git clone https://github.com/tensorflow/tensorflow.git

Depois deveremos proceder da seguinte forma:

tensorflow/contrib/makefile/download_dependencies.sh
sudo apt-get install -y autoconf automake libtool gcc-4.8 g++-4.8
cd tensorflow/contrib/makefile/downloads/protobuf/
./autogen.sh
./configure
make CXX=g++-4.8
sudo make install
sudo ldconfig # refresh shared library cache
cd ../../../../..
export HOST_NSYNC_LIB=`tensorflow/contrib/makefile/compile_nsync.sh`
export TARGET_NSYNC_LIB="$HOST_NSYNC_LIB"

O comando make CXX=g++-4.8 está diferente das instruções da página do github sobre a compilação das sources do tensorflow, porque sem a indicação da versão do g++, a compilação do tensorflow (efectuada depois da compilação do protoc) termina com o seguinte erro:

collect2: error: ld returned 1 exit status
tensorflow/contrib/makefile/Makefile:566: recipe for target '/home/sensor1/tensorflow/tensorflow/contrib/makefile/gen/bin/benchmark' failed
make: *** [/home/sensor1/tensorflow/tensorflow/contrib/makefile/gen/bin/benchmark] Error 1

Com base na informação do seguinte link:

https://github.com/tensorflow/tensorflow/issues/13176

Experimentei o compilar o protoc com a inclusão da versão do gcc no comando make, e o resultado foi bom pois além da compilação do protoc correr sem problemas, a do tensorflow também já não deu erro.

 

Raspberry Pi 1

make -f tensorflow/contrib/makefile/Makefile HOST_OS=PI TARGET=PI OPTFLAGS="-Os" CXX=g++-4.8

Raspberry Pi 2/3

make -f tensorflow/contrib/makefile/Makefile HOST_OS=PI TARGET=PI \
OPTFLAGS="-Os -mfpu=neon-vfpv4 -funsafe-math-optimizations -ftree-vectorize" CXX=g++-4.8

 

Instalação da detecção de objectos

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md

 

 

 

https://github.com/EdjeElectronics/TensorFlow-Object-Detection-on-the-Raspberry-Pi

Tensorflow Install

apt-get install libatlas-base-dev
mkdir tf
cd tf

wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp35-none-linux_armv7l.whl

pip3 install /home/pi/tf/tensorflow-1.8.0-cp35-none-linux_armv7l.whl

Tensorflow object recognition requirements

apt-get install libfreetype6-dev pkg-config libxml2-dev libxslt1-dev

pip3 install pillow lxml jupyter matplotlib cython

pip3 install pygments

pip3 install bleach

pip3 install jsonschema>2.5.0

pip3 install jupyter

apt-get install python-tk

 

openCV

apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev
apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
apt-get install libxvidcore-dev libx264-dev
apt-get install qt4-dev-tools

pip3 install opencv-python

Install Protobuf

apt-get install autoconf automake libtool curl

wget https://github.com/protocolbuffers/protobuf/releases/download/v3.8.0/protobuf-all-3.8.0.tar.gz

./configure

make (1H)

make test (101 min. can skip)

make install

cd python
export LD_LIBRARY_PATH=../src/.libs

 

python3 setup.py build –cpp_implementation
python3 setup.py test –cpp_implementation
sudo python3 setup.py install –cpp_implementation

export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp
export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION=3

ldconfig

protoc

reboot now

Set up TensorFlow Directory Structure and PYTHONPATH Variable

mkdir tensorflow1
cd tensorflow1

git clone –recurse-submodules https://github.com/tensorflow/models.git

nano ~/.bashrc

(insert as last line)

export PYTHONPATH=$PYTHONPATH:/home/pi/tensorflow1/models/research:/home/pi/tensorflow1/models/research/slim

cd models/research

protoc object_detection/protos/*.proto –python_out=.

cd object_detection

wget http://download.tensorflow.org/models/object_detection/ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz
tar -xzvf ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz

 

Links

https://github.com/lhelontra/tensorflow-on-arm

https://www.oreilly.com/learning/how-to-build-a-robot-that-sees-with-100-and-tensorflow

https://github.com/lukas/robot

https://github.com/EdjeElectronics/TensorFlow-Object-Detection-on-the-Raspberry-Pi#2-install-tensorflow

https://github.com/tfors/rpi-tf