<구성 환경>
Visual Studio 2015 Community Update 3
boost_1_65
Anaconda Virtual Environment Python 3.5.x
<참고자료>
3. 텐서플로우(TensorFlow)를 이용한 MNIST 문자 인식 프로그램 만들기
http://solarisailab.com/archives/303
Tensorflow FCNN C++로만 구현하기
http://blog.naver.com/atelierjpro/221056571787
Boost Python으로 Tensorflow를 C++에서 더 쉽게 쓰기
C++로 옮길 MNIST의 파이썬 코드 예제입니다.
# -*- coding: utf-8 -*- # MNIST 데이터를 다운로드 한다. from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # TensorFlow 라이브러리를 추가한다. import tensorflow as tf # 변수들을 설정한다. x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) # cross-entropy 모델을 설정한다. y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) print(train_step) # 경사하강법으로 모델을 학습한다. init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) #sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) sess.run(train_step, feed_dict={x : batch_xs, y_ : batch_ys}) # 학습된 모델이 얼마나 정확한지를 출력한다. correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) | cs |
제가 C++로 옮겨본 소스입니다.
초반에는 exec과 eval를 일부러 많이 쓰다가 점점 익숙해지면서 최대한 exec과 eval을 줄여보려고 했습니다.
하지만 mnist에 대한 데이터를 py::object 객체로 받아온 것은 좋았는데 그 이후에 mnist.train.next_batch(100) 줄을 실행할 때 배열의 인덱스는 특정한 정수여야한다는 에러가 떠서 그냥 파이썬 모듈에서도 import 시켜주고 eval로 받아왔습니다.
#define BOOST_PYTHON_STATIC_LIB #define BOOST_LIB_NAME "boost_numpy3" #include <boost/config/auto_link.hpp> #include <boost/python.hpp> #include <boost/python/numpy.hpp> #include <iostream> namespace py = boost::python; namespace np = boost::python::numpy; int main() { using namespace std; try { Py_SetPythonHome(L"D:\\Equip\\Anaconda3\\envs\\py35_tf_cpp"); Py_Initialize(); np::initialize(); PyRun_SimpleString("#-*- coding: utf-8 -*-"); py::object main_module = py::import("__main__"); py::object main_namespace = main_module.attr("__dict__"); py::object sys_ = py::import("sys"); PyRun_SimpleString("import sys\n" "sys.argv = ['']"); py::object print = py::import("__main__").attr("__builtins__").attr("print"); const py::object tf_ = py::import("tensorflow"); py::exec("import tensorflow as tf", main_namespace); const py::object input_data_ = py::import("tensorflow.examples.tutorials.mnist").attr("input_data"); py::object mnist = input_data_.attr("read_data_sets")("MNIST_data", true); py::exec("from tensorflow.examples.tutorials.mnist import input_data", main_namespace); py::exec("mnist = input_data.read_data_sets('MNIST_data /', one_hot=True)", main_namespace); //Set variables py::object x = py::eval("tf.placeholder(tf.float32, [None, 784])", main_namespace); py::object W = py::eval("tf.Variable(tf.zeros([784, 10]))", main_namespace); py::object b = py::eval("tf.Variable(tf.zeros([10]))", main_namespace); py::object y = tf_.attr("nn").attr("softmax")(tf_.attr("matmul")(x, W) + b); //Set Cross-Entropy Model py::object y_ = py::eval("tf.placeholder(tf.float32, [None, 10])", main_namespace); py::object sum = tf_.attr("reduce_sum")(y_ * tf_.attr("log")(y), 1); py::object cross_entropy = tf_.attr("reduce_mean")(-1 * sum); py::object train_step = tf_.attr("train").attr("GradientDescentOptimizer")(0.5).attr("minimize")(cross_entropy); // Learn model using SGD py::object init = tf_.attr("initialize_all_variables")(); py::object sess = tf_.attr("Session")(); sess.attr("run")(init); for (int i = 0; i < 1000; i++) { py::object batches = py::eval("mnist.train.next_batch(100)", main_namespace); py::object batch_xs = batches[0]; py::object batch_ys = batches[1]; py::dict feed_dict; feed_dict[x] = batch_xs; feed_dict[y_] = batch_ys; sess.attr("run")(train_step, feed_dict); } // Print Accuracy py::object f32 = tf_.attr("float32"); py::object correct_prediction = tf_.attr("equal")(tf_.attr("argmax")(y, 1), tf_.attr("argmax")(y_, 1)); py::object cast = tf_.attr("cast")(correct_prediction, f32); py::object accuracy = tf_.attr("reduce_mean")(cast); py::dict feed_dict; py::object test_x = py::eval("mnist.test.images", main_namespace); py::object test_y = py::eval("mnist.test.labels", main_namespace); feed_dict[x] = test_x; feed_dict[y_] = test_y; print(sess.attr("run")(accuracy, feed_dict)); } catch (py::error_already_set&) { PyErr_Print(); system("pause"); } return 0; } | cs |
실행하면 아래와 같은 결과를 얻을 수 있습니다.
Extracting MNIST_data /train-images-idx3-ubyte.gz
Extracting MNIST_data /train-labels-idx1-ubyte.gz
Extracting MNIST_data /t10k-images-idx3-ubyte.gz
Extracting MNIST_data /t10k-labels-idx1-ubyte.gz
(Warning 및 GPU 정보 생략)
0.9189
'연구 > 딥러닝' 카테고리의 다른 글
Visual Studio에서 C++로 TensorFlow 실행하기 (3) | 2017.08.28 |
---|