출처: https://seanpaulskin.tistory.com/entry/부스트-라이브러리Boost-Library-VC과-MinGW-컴파일Compile-하기 [:: 스킨 테스트 블로그 :: HTML5 / XHTML / HTML / CSS]

 

 

1. 부스트 라이브러리 최신 버전이나 필요한 버전을 다운 받는다.

- 이 글 작성시 부스트 최신 버전 : 1_58_0 

부스트 공식 홈( http://www.boost.org ) 또는 

SourceForge 다운로드  http://sourceforge.net/projects/boost/files/

 

컴파일을 하지 않고 바로 사용 할려면 컴파일된 x32, 또는 x64 파일을 다운
http://sourceforge.net/projects/boost/files/boost-binaries/1.58.0/

Boost_1_58_0-bin-msvc-all-32-64.7z 1.3GB (x32, x64 비주얼 스튜디오 모든 버전 포함)

 

 

 

Visual Studio 2013 크로스 컴파일러를 설치하면  

여러 가지 커맨드 프롬프트 제공 합니다. ( Itanium 버전은 인텔의 개발 중지 발표로 생략)

 

x64 크로스 Tools 명령 프롬프트에서는 x86환경에서 x64 컴파일 가능.

x86, x64 네이티브에서는 각 각  x32 , x64 컴파일 가능.

 

*** 미리 컴파일된 버전을 사용하지 않고 직접 컴파일해서 사용 하고자 한다면 ***

Boost 라이브러리는 두가지 방법으로 컴파일 할 수 있는데,

1. 헤더 파일과 라이브러리를 생성하는 방법
2. 라이브 러리를 생성 하는 방법

처음 설치 한다면 헤더(Header)와 라이브러리(Library)가 필요 하므로 install 옵션을 쓰고 

추가적으로 라이브러리(Library)가 필요하다면 stage를 쓰면 됩니다.

 

 

부스트 라이브러리 루트 폴더에 boostrap.bat 실행해서 b2.exe와 bjam.exe를 생성 합니다.

2개다 같은 일을 하지만 여기서는 b2.exe으로 설명 합니다.

b2 [options] [properties] [install|stage]

VS 2013 기준(msvc-12.0), VS 2012 : msvc-11.0)

 

--stagedir (라이브러리 파일이 있는 stage 폴더내에 복사

--libdir을 지정 해주면 원하는 폴더로 복사( --libdir="C:\Boost\lib" )

--includedir 위 와 마찬가지( --includedir="C:\Boost\include" )

-j n - CPU 멀티 코어 사용 ( n : 코어 갯수 지정 )

 

x32 라이브러리

/MT, /MTd (멀티 스레드 릴리즈, 멀티 스레드 디버그) : 정적 라이브러리 생성( .LIB )

b2  --stagedir=stage32 --toolset=msvc-12.0 -j 4 runtime-link=static

 

/MD, /MDd (멀티 다이나믹, 멀티 다이나믹 디버그  ): 동적 라이브러리 생성( .DLL )

b2  --stagedir=stage32 --toolset=msvc-12.0 -j 4 runtime-link=shared

 

x64 라이브러리

/MT, /MTd (멀티 스레드 릴리즈, 멀티 스레드 디버그) : 정적 라이브러리 생성

b2  --stagedir=stage64 address-model=64 --toolset=msvc-12.0 -j 4 runtime-link=static

 

/MD, /MDd

b2  --stagedir=stage64 address-model=64 --toolset=msvc-12.0 -j 4 runtime-link=shared

 

컴파일 결과파일 이름(Naming) 규칙

- lib 접두사 - Win32에서 Static 라이브러리에 붙음.

- boost - 접두사 모든 파일 앞에 붙음.

- vc120 - 비주얼 스튜디오 버전별로( 2012 : vc110, 2010 : vc100 )

 

- mt - Shared 멀티 스레드용(multi-threading) 릴리즈 버전 

- mt-gd Shared 방식으로 멀티 스레드용(multi-threading) 디버그 버전

- mt-s Static 방식으로 릴리즈

- mt-sgd  Static multi-threading 디버그 버전

- 1_58 - 부스트 버전.

- .lib - 확장자

 


 

컴파일 예제 :

C:\Boost에 Visual Studio 2013버전 x32, x64 디버그, 릴리즈 

싱글, 멀티스레딩(정적, 동적 라이브러리)를 멀티코어 4개로 컴파일

 

b2  --libdir="C:\Boost\lib" --libinclude="C:\Boost\include"

 --toolset=msvc-12.0 variant=debug,release address-model=32,64 

threading=single,multi -j 4 runtime-link=static,shared

컴파일 결과 : C:\Boost\Lib, C:\Boost\Include 생성 lib 폴더내에 .lib, .dll 파일 생성




import tensorflow.compat.v1 as tf
import numpy as np
import random
import time
import matplotlib.pyplot as plt


tf.disable_v2_behavior()
 

tf.set_random_seed(777)  # for reproducibility

from tensorflow.examples.tutorials.mnist import input_data


# Check out https://www.tensorflow.org/get_started/mnist/beginners for
# more information about the mnist dataset
mnist = input_data.read_data_sets("D:/Downloads/", one_hot=True)

sizeof_x = 784
nb_classes = 10
nb_branch = 256
epoch = 15
batch_size = 100
alg = 4
val_keep_prob = 1.0


num_iterations = int(mnist.train.num_examples / batch_size)



x_data = tf.placeholder(tf.float32, [None, sizeof_x])
y_data = tf.placeholder(tf.float32, [None, nb_classes])
keep_prob = tf.placeholder(tf.float32)



if alg == 0 :
    print("Using single network.. softmax + GradientOptimizer")
    W1 = tf.Variable(tf.random_normal([sizeof_x, nb_classes]), name="weight1")
    B1 = tf.Variable(tf.random_normal([nb_classes]), name="bias1")
    logits = tf.matmul(x_data, W1) + B1
    H = tf.nn.softmax(logits)
     
    cost = tf.reduce_mean(-tf.reduce_sum(y_data * tf.log(H), axis=1))
    train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)

if alg == 1 :
    print("Using single network.. softmax + AdamOptimizer1")
    W1 = tf.Variable(tf.random_normal([sizeof_x, nb_classes]), name="weight1")
    B1 = tf.Variable(tf.random_normal([nb_classes]), name="bias1")
    
    logits = tf.matmul(x_data, W1) + B1
    H = tf.nn.softmax(logits)
 
    cost = tf.reduce_mean(-tf.reduce_sum(y_data * tf.log(H), axis=1))
    train = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

if alg == 2 :
    print("Using single network.. softmax + AdamOptimizer2")
    W1 = tf.Variable(tf.random_normal([sizeof_x, nb_classes]), name="weight1")
    B1 = tf.Variable(tf.random_normal([nb_classes]), name="bias1")

    H = tf.matmul(x_data, W1) + B1
    
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=H, labels=y_data))
    train = tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost)

elif alg == 3:
    print("Using neural network.. relu + AdamOptimizer")
    W1 = tf.Variable(tf.random_normal([sizeof_x, nb_branch]), name="weight1")
    B1 = tf.Variable(tf.random_normal([nb_branch]), name="bias1")
    
    W2 = tf.Variable(tf.random_normal([nb_branch, nb_branch]), name="weight2")
    B2 = tf.Variable(tf.random_normal([nb_branch]), name="bias2")
    
    W3 = tf.Variable(tf.random_normal([nb_branch, nb_classes]), name="weight3")
    B3 = tf.Variable(tf.random_normal([nb_classes]), name="bias3")
    
    L1 = tf.nn.relu(tf.matmul(x_data, W1) + B1)
    L2 = tf.nn.relu(tf.matmul(L1, W2) + B2)
    H = tf.matmul(L2, W3) + B3
    
    # cross entropy
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=H, labels=tf.stop_gradient(y_data)))
    train = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
  

elif alg == 4:
    nb_branch = 512
    val_keep_prob = 0.7
    
    print("Using Deep neural network.. dropout")
    W1 = tf.Variable(tf.random_normal([sizeof_x, nb_branch]), name="weight1")
    B1 = tf.Variable(tf.random_normal([nb_branch]), name="bias1")
    W2 = tf.Variable(tf.random_normal([nb_branch, nb_branch]), name="weight2")
    B2 = tf.Variable(tf.random_normal([nb_branch]), name="bias2")
    W3 = tf.Variable(tf.random_normal([nb_branch, nb_branch]), name="weight3")
    B3 = tf.Variable(tf.random_normal([nb_branch]), name="bias3")
    W4 = tf.Variable(tf.random_normal([nb_branch, nb_branch]), name="weight4")
    B4 = tf.Variable(tf.random_normal([nb_branch]), name="bias4")    
    W5 = tf.Variable(tf.random_normal([nb_branch, nb_classes]), name="weight5")
    B5 = tf.Variable(tf.random_normal([nb_classes]), name="bias5")
    
    L1 = tf.nn.relu(tf.matmul(x_data, W1) + B1)
    L1= tf.nn.dropout(L1, keep_prob=keep_prob)
    L2 = tf.nn.relu(tf.matmul(L1, W2) + B2)
    L2= tf.nn.dropout(L2, keep_prob=keep_prob)
    L3 = tf.nn.relu(tf.matmul(L2, W3) + B3)
    L3= tf.nn.dropout(L3, keep_prob=keep_prob)
    L4 = tf.nn.relu(tf.matmul(L3, W4) + B4)
    L4 = tf.nn.dropout(L4, keep_prob=keep_prob)
    H = tf.matmul(L4, W5) + B5
    
    # cross entropy
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=H, labels=tf.stop_gradient(y_data)))
    train = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
    

is_correct = tf.equal(tf.argmax(y_data, 1), tf.argmax(H, 1))
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))


sess = tf.Session()
sess.run(tf.global_variables_initializer())

for e in range(epoch):
    avg_cost = 0
    for it in range(num_iterations):
        x_batch, y_batch = mnist.train.next_batch(batch_size)
        val_cost, acc, _ = sess.run([cost, accuracy, train], feed_dict={x_data:x_batch, y_data:y_batch, keep_prob:val_keep_prob})
        avg_cost = avg_cost + val_cost / num_iterations
        
    print("Epoch: {:04d}, Cost: {:.9f}".format(e + 1, avg_cost))
    
print("training finished")


val_keep_prob = 1.0
print("Accuracy: ", accuracy.eval(session=sess, feed_dict={x_data: mnist.test.images, y_data: mnist.test.labels, keep_prob:val_keep_prob}))

for i in range(1):
    r = random.randint(0, mnist.test.num_examples - 1)
    label= sess.run( tf.argmax( mnist.test.labels[r:r+1], 1 ))
    image= mnist.test.images[r:r+1]
    predict= sess.run(tf.argmax(H, 1), feed_dict={x_data: image, keep_prob:val_keep_prob})
    print("{} {} Label={} Predict={}".format(i, label==predict, label, predict))
    plt.imshow(image.reshape(28, 28),        cmap="Greys",
        interpolation="nearest"
        )
    plt.show()
    time.sleep(3)

나님을 위해 향후 잊어먹을경우를 위해 기억을 저장해 둔다.

WIN10에서 아나콘다로 tensorflow를 설치한 경우이다.

본인과 설치 환경이 다를 수 있으므로 안된다고 묻지 마세요.

 

Tensorflow로 MNIST 테스트 하려고 하는데 다음과 같은 오류로 에러가 발생하면서 안될 때 해결 방법을 설명한다.

 

 

input_data라고 하는 녀석을 찾을 수 없다고 하는데...

아나콘다로 설치하면 tensorflow.examples.tutorials 폴더 내 mnist폴더 조차 없다.

아나콘다 환경 설정에서도 설치할 수 없었다.

그래서 나는 수동 설치 했다.

즉, input_data.py 파일을 직접 수동으로 다운로드 해서 tensorflow의 해당 경로에 설치하도록 한다.

 

 

1. input_data.py 파일이 있는 github 소스 페이지로 이동.

   [input_data.py 파일 위치로 바로 가기]

 

2. Raw 파일 버튼을 눌러서 파일 내용을 열람한다.

3. 파일 내용을 복사하고 메모장을 열어 붙여넣기 한 후 input_data.py라는 파일 이름으로 저장한다.

    저장 후 나중에 찾기 쉽도록 "바탕화면"에 저장한다.

 

 

4. 윈도 탐색기를 실행하고 Tensorflow가 설치된 위치로 이동한다.

위 폴더 위치가 바로 아래 코드의 examples 위치이다.

from tensorflow.examples.tutorials.mnist import input_data

tensorflow가 바로 tensorflow_core 폴더와 같다.

나머지 examples는 examples 폴더와 같다.

그렇다면 나머지 tutuorials와 mnist 폴더를 만들고 그 밑에 input_data.py 파일을 집어넣으면 되겠다.

 

 

5. 폴더 만들고 input_data.py 파일 집어넣기.

 

6. 이제 소스 실행하면 문제 없이 실행된다.

 

 

Happy hacking~!

+ Recent posts