2015년 8월 5일 수요일

Windows에서 Theano 설치

첫 번째 방법

Windows7 64bit 와 vs2013 사용 환경에서 설치


1. Anaconda(python) 설치.  https://store.continuum.io/cshop/anaconda/

>conda update conda // update 해줌
>conda install mkl  // intel math kernel lib, blas 중 하나
>conda install libpython // gcc, g++ 컴파일러 설치, gcc는 theano 컴파일에 필요

libpython 설치 후에도 gcc가 실행되지 않으면, 아래에서처럼 MinGW, MSYS를 직접 설치할 수 있다.  MinGW와 MSYS는 windows 환경에서 Linux 환경을 사용 가능하게 해 줌.
또 다른 자료에는
>conda install mingw libpython
잘 동작 한다고 하나 시도해보지 않았음.


2. Visual studio 2013 설치.
설치 후에 vs의 cl.exe(ms의 c/c++ 컴파일러/링크 제어 명령)를 사용해야 하므로 path를 설정해야 함.  "시작 버튼->내컴퓨터->오른쪽 클릭->속성->고급시스템설정->환경변수->'시스템변수'->'Path'->편집 버튼" 에서 경로 추가.  보통 cl.exe는 C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin에 있음.

windows 64bit를 사용하므로 cmd창을 열고 cl이 있는 위치로 가서 x64 설정:
>cd C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC
>vcvarsall.bat amd64

설정 후, cmd 창에서 cl입력해서 x64(64bit compiler/link)인지 확인. cl은 cuda 컴파일에 필요


3. cuda 설치 (7.0버전)


4. Theano 설치
기 설치된 anaconda의 console을 하나 open한다. cl.exe의 64bit 옵션은 현재 오픈된 해당 console에서만 유효하므로 x64로 변경 후

> where cl
> where gcc 
> where nvcc
> where g++

로 여러 컴파일러들이 문제 없이 동작함을 확인한다.

> pip install theano 

로 theano 설치 (제거 시에는 >pip uninstall theano, 기 설치의 upgrade는 >pip install --upgrade theano). 혹시 더 필요한 lib가 있다면 이런 방식으로 설치나 제거해준다.


5. Theano 설치 후

cmd 창에서 

>echo %USERPROFILE%

해서 위치 확인하고 거기로(user 디렉토리임) 가면 ".theanorc.txt' 파일이 있다. 이것을 아래처럼 수정. 없다면 새로 만듬.
---------------
[global]
device = gpu
floatX = float32

[nvcc]
flags=--use-local-env --cl-version=2013
----------------



6. Test 1

> python

실행 후 

>> import theano
>> theano.test()

명령 입력. 두번째 명령은 theano 실행에 필요한 여러 소스를 알아서 컴파일 한다(상당히 오래 걸림). 미리 컴파일 해놓지 않으면 iphython notebook 등에서 theano 실행 시 오래 걸리거나 오류 발생 (실행전 cl의 x64 체크).



7. Test 2
아래 두 번째 방법의 6번 수행.
(일단 새 console 창 열면 무조건 cl을 x64로 설정해 줘야 함)


8. Test 3 [1]
interactive python(ipython ) notebook 실행 후 theano 사용과 graph 출력:

%matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

import theano
import theano.tensor as T





MinGW와 MSYS의 직접 설치

만일 gcc가 제되로 실행되지 않는다면 다음처럼 mingw와 msys를 설치한다.

1. 64bit MinGWMSYS를 설치한다. (둘 다 설치 파일 MinGW-w64 installer.exe 와 MSYS-1.0.11.exe를 받아 실행)
-MinGW: Architecture(x86_64), Thread(posix), Exception(Seh)로 설정. 설치 directory는 "c:\MinGW"로 간략하게 함. 설치 중간 옵션 중에 g++ compiler 선정.
-MSYS: 설치 경로를 "c:\MSYS"로 단순하게 함. 설치 중간에 물음에 y선택 2번, MinGW 경로 요구는 "c:/MinGW"(MinGW설치 경로. 이 밑으로 bin 등이 있어야 함) 설정.


2. 시스템 속성 변경

환경변수->시스템변수.에 와서 '새로만들기' 선택.  변수명(MINGW), 변수값(c:\\MinGW). 또, 변수명(MSYS), 변수값(c:\\msys) 입력.
'Path' 항목 찾아 편집 버턴을 눌러 %MINGW%\bin;%MSYS%\bin; 추가 후. 클릭.

완료 했으면 cmd창을 열어서 다음을 입력하여 확인.
>make
>gcc --version

 
cuda, cl, gcc, g++ 설치가 잘 되었는지 확인 방법: cmd창 열어
>where cl
>where gcc
>where g++
>where nvcc






두 번째 방법

1. 먼저 libpythonxx.a 파일을 만들어야 한다. 일단 pythonxx.dll(2.7 version의 경우 python27.dll. c:\anaconda밑에 있다)을 찾아서 임시 directory에 복사.

2. 다음 명령을 실행(여기서 XX는 버전 정보 27)
>gendef pythonXX.dll
>dlltool --as-flags=--64 -m i386:x86-64 -k --output-lib libpythonXX.a --input-def pythonXX.def

3. 이렇게 만들어진 libpythonxx.a 파일을 파이썬을 설치한 directory의 libs 아래에 복사.  여기서는
c:\anaconda\libs 밑에 복사.

4. https://github.com/Theano/Theano에 가서 Theano의 zip파일을 다운 받아서 압축을 푼다. Theano 코드가 있는 directory에서
>pip install .


5. cmd창에서
>echo %USERPROFILE%
해서 위치 확인하고 거기로(보통 user 디렉토리임) 가면 ".theanorc.txt'파일이 있다. 이것을 수정. 없다면 새로 만듬.
---------------
[blas]
ldflags =

[gcc]
cxxflags = -shared -I[MinGW 디렉토리]\include -L[파이썬 디렉토리]\libs -lpython34 -DMS_WIN64
----------------


직접 설정한 예는 다음과 같다:
----------------
[blas]
ldflags =

[gcc]
cxxflags = -shared -I%MINGW%\include -LC:\Anaconda\libs -lpython27 -DMS_WIN64

[global]
device = gpu
floatX = float32

[nvcc]
flags=--use-local-env --cl-version=2013
-----------------

device는 cpu나 gpu로 바꿀 수 있다.



6. 테스트를 위해 Anaconda command prompt를 하나 열고
>python test.py

해보면 된다.
test.py파일은 http://hugman.re.kr/static/media/uploads/codes/test.py 에 있다.

---------------------------------
import numpy as np
import time
import theano
A = np.random.rand(1000,10000).astype(theano.config.floatX)
B = np.random.rand(10000,1000).astype(theano.config.floatX)
np_start = time.time()
AB = A.dot(B)
np_end = time.time()
X,Y = theano.tensor.matrices('XY')
mf = theano.function([X,Y],X.dot(Y))
t_start = time.time()
tAB = mf(A,B)
t_end = time.time()
print "NP time: %f[s], theano time: %f[s] (times should be close when run on CPU!)" %(
                                           np_end-np_start, t_end-t_start)
print "Result difference: %f" % (np.abs(AB-tAB).max(), )
----------------------------------

실행 하면 다음과 같은 결과가 나온다:

2015년 8월 2일 일요일

Color data augmentation in Alexnet

clc; clear all;
im=imread('painter.jpg'); % 이미지 입력
imd=double(im)/255.0; % 픽셀 값을 0~1사이의 실수 값으로 만듬

m = size(imd,1); % 이미지 폭
n = size(imd,2); % 높이. 한번에 [m,n] =size(imd);로 해도 됨
im1=reshape(imd(:,:,1),[1,m*n]); % r 행렬을 벡터로 변환
im2=reshape(imd(:,:,2),[1,m*n]); % g
im3=reshape(imd(:,:,3),[1,m*n]); % b

m1=mean(im1); m2=mean(im2); m3=mean(im3); % r, g, b 각 채널 픽셀 값의 평균
d1=im1-repmat(m1,[1,m*n]); % r 픽셀 값에서 r 평균을 뺌
d2=im2-repmat(m2,[1,m*n]);
d3=im3-repmat(m3,[1,m*n]);

data=[d1' d2' d3']; % 크기가 [m*n, 3] 임. 분포의 중심을 원점으로 분포 행렬 만듬
[v,d]=eig(data'*data); % 데이터의 분산이 큰 방향(v)과 크기(d) 얻음

dv=sqrt(diag(d)); % 퍼짐의 크기
val=v*(0.1*randn(3,1).*dv); % 정규분포(0.1의 분산)에서 하나의 랜덤 샘플링 값을 얻고 dv에 곱합. v 방향으로 이 크기 만큼 변형된 r, g, b 값 추출. val 값을 원 r,g,b 데이터에 더해서 color aug 이미지를 만들어 냄.



References
[1] Alex Krizhevsky et. al., ImageNet Classification with Deep Convolutional Neural Networks, 2012.