라즈베리파이 텐서플로우 설치하는 법

텐서플로우 설치

라즈베리파이에 텐서플로우 설치하기

굳이 왜 라즈베리파이에 텐서플로우를 설치하지? 라고 묻는다면 특별히 뭐라 대답할 말이 떠오르지 않지만, 그냥 시간이 많이 남을 때 재미로(?) 설치하는 거야 정도로 대답할 수 있습니다.


실제로 라즈베리파이에 텐서플로우를 설치하는 것은 10시간 이상 소요되기 때문에, 정말 시간이 많고 할일이 없을 때 시도해볼만 합니다.


그나마 다행인것은 10시간 내내 PC앞에 앉아 있을 필요는 없다는 것입니다. 실제 사람이 작업해주는 과정은 1시간 내외이며 나머지 시간은 설치, 빌드를 기다리는 시간이기 때문에 굳이 PC앞에 앉아 있을 필요는 없습니다.


작업을 시작하기 위해서 필요한 준비물은, 라즈베리파이(설치 시간을 단축하기 위해 최신모델인 라즈베리파이3 권장)와 16GB MicroSD카드, 1GB 이상의 USB 메모리가 필요합니다.


설치는 총 4단계로 나눌 수 있는데


  1. 라즈베리파이 업데이트 및 최신 패키지 설치
  2. 추가 스왑파일을 위한 USB메모리 설정
  3. Bazel 컴파일 및 설치
  4. Tensor 컴파일 및 설치


이 단계에서 가장 고통(?)스러운 과정은 Google의 Java 기반 빌드시스템인 Bazel을 설치하는 것인데, 8~10시간 정도 소요된다고 합니다.


그럼 단계별 설치법에 대해서 알아보겠습니다.

(불펌 방지로 마우스 오른쪽버튼을 막아놨는데, http://smartaedi.tistory.com/m/290 접속하시면 복사하기가 풀립니다.)



1. 라즈베리파이 업데이트 및 최신 패키지 설치


먼저, apt-get으로 업데이트할 자료 목록을 다운로드 합니다.

sudo apt-get update


다음 Bazel 설치를 위한 종종석 및 Tool 들을 설치합니다.

sudo apt-get install pkg-config zip g++ zlib1g-dev unzip


파이선 설치(2.7이나 3.3+ 중 원하는 버전을 설치하세요.)

# For Python 2.7

sudo apt-get install python-pip python-numpy swig python-dev

sudo pip install wheel



# For Python 3.3+

sudo apt-get install python3-pip python3-numpy swig python3-dev

sudo pip3 install wheel


최적화 플래그 사용을 위한 설정

sudo apt-get install gcc-4.8 g++-4.8

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 100

sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 100


설치 디렉토리 생성

mkdir tf

cd tf


2. USB메모리 설정


USB메모리를 꼽고 장치의 경로를 확인(/dev/XXX 의 위치로 인식되며 보통 /dev/sda1로 인식됨)

sudo blkid


메모리가 인식됏다면 언마운트 시킨 후 포맷

sudo umount /dev/XXX

sudo mkswap /dev/XXX


메모리의 UUID를 확인

sudo blkid


/etc/fstab 파일 편집

sudo nano /etc/fstab


fastab 파일 제일 하단에 아래 라인 추가

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


스왑 기능 활성화 및 확인

sudo swapon -a

free -h



3. Bazel 컴파일 및 설치


Bazel 빌드를 위한 배포 아카이브 파일 다운로드

wget https://github.com/bazelbuild/bazel/releases/download/0.4.5/bazel-0.4.5-dist.zip

unzip -d bazel bazel-0.4.5-dist.zip

cd bazel


javac 최대 힙파일 크기 변경

nano scripts/bootstrap/compile.sh


117 Line을 다음과 같이 수정(빨간색)

run "${JAVAC}" -classpath "${classpath}" -sourcepath "${sourcepath}" \

-d "${output}/classes" -source "$JAVA_VERSION" -target "$JAVA_VERSION" \

-encoding UTF-8 "@${paramfile}" -J-Xmx500M


빌드옵션 설정

nano tools/cpp/cc_configure.bzl


133 Line을 다음과 같이 수정(빨간색)

"""Compute the cpu_value based on the OS name."""

return "arm"


Bazel 빌드(주의! 상당한 시간이 소요되므로, 자기전 실행하는게 좋음)

sudo ./compile.sh


빌드가 끝난 Bazel 파일 복사

sudo cp output/bazel /usr/local/bin/bazel


제대로 설치됐는지 확인을 위해 Bazel 실행(녹색 화면이 나오면 성공)

bazel


Usage: bazel <command> <options> ...


Available commands:

analyze-profile Analyzes build profile data.

build Builds the specified targets.

canonicalize-flags Canonicalizes a list of bazel options.

clean Removes output files and optionally stops the server.

dump Dumps the internal state of the bazel server process.

fetch Fetches external repositories that are prerequisites to the targets.

help Prints help for commands, or the index.

info Displays runtime info about the bazel server.

mobile-install Installs targets to mobile devices.

query Executes a dependency graph query.

run Runs the specified target.

shutdown Stops the bazel server.

test Builds and runs the specified test targets.

version Prints version information for bazel.


Getting more help:

bazel help <command>

Prints help and options for <command>.

bazel help startup_options

Options for the JVM hosting bazel.

bazel help target-syntax

Explains the syntax for specifying targets.

bazel help info-keys

Displays a list of keys used by the info command.


상위 디렉토리로 이동

cd ..



4. 텐서플로우 컴파일 및 설치


텐서플로우 저장소 복제 및 생성된 디렉토리 이동

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

cd tensorflow


64비트 프로그램을 32비트로 변경

grep -Rl 'lib64' | xargs sed -i 's/lib64/lib/g'


종속성 변경

sudo nano tensorflow/workspace.bzl


이 부분을 아래와 같이 수정

#원본

native.new_http_archive(

name = "eigen_archive",

urls = [

"http://mirror.bazel.build/bitbucket.org/eigen/eigen/get/f3a22f35b044.tar.gz",

"https://bitbucket.org/eigen/eigen/get/f3a22f35b044.tar.gz",

],

sha256 = "ca7beac153d4059c02c8fc59816c82d54ea47fe58365e8aded4082ded0b820c4",

strip_prefix = "eigen-eigen-f3a22f35b044",

build_file = str(Label("//third_party:eigen.BUILD")),

)


#수정

native.new_http_archive(

name = "eigen_archive",

urls = [

"http://mirror.bazel.build/bitbucket.org/eigen/eigen/get/d781c1de9834.tar.gz",

"https://bitbucket.org/eigen/eigen/get/d781c1de9834.tar.gz",

],

sha256 = "a34b208da6ec18fa8da963369e166e4a368612c14d956dd2f9d7072904675d9b",

strip_prefix = "eigen-eigen-d781c1de9834",

build_file = str(Label("//third_party:eigen.BUILD")),

)


빌드 구성

./configure


Please specify the location of python. [Default is /usr/bin/python]: /usr/bin/python

Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]:

Do you wish to use jemalloc as the malloc implementation? [Y/n] Y

Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] N

Do you wish to build TensorFlow with Hadoop File System support? [y/N] N

Do you wish to build TensorFlow with the XLA just-in-time compiler (experimental)? [y/N] N

Please input the desired Python library path to use. Default is [/usr/local/lib/python2.7/dist-packages]

Do you wish to build TensorFlow with OpenCL support? [y/N] N

Do you wish to build TensorFlow with CUDA support? [y/N] N


텐서플로우 빌드(주의! 상당한 시간이 소요되므로, 자기전에..)

bazel build -c opt --copt="-mfpu=neon-vfpv4" --copt="-funsafe-math-optimizations" --copt="-ftree-vectorize" --copt="-fomit-frame-pointer" --local_resources 1024,1.0,1.0 --verbose_failures tensorflow/tools/pip_package:build_pip_package


파이선휠 생성 및 텐서플로우 설치(다음날 아침)

bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

sudo pip install /tmp/tensorflow_pkg/tensorflow-1.1.0-cp27-none-linux_armv7l.whl


스왑했던 USB메모리 제거

sudo swapoff /dev/XXX


fstab 파일 원복

sudo nano /etc/fstab


#제일끝 줄 삭제

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


이제 라즈베리파이를 리부팅 하시면 텐서플로우 사용이 가능합니다.


예측소요시간은 이미지 로딩 및 인식 15~20초, 텐서플로우 라이브러리 로딩은 약 30초가 걸린다고 합니다.


라즈베리파이 텐서플로우 화면

라즈베리파이 텐서플로우 설치는 아래 영상이나 Github를 참고하셔도 좋습니다.




댓글

Designed by JB FACTORY