1. Tensorflow 2.X Ver#1

import gym
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

env = gym.make('FrozenLake-v0')


learning_rate = 0.1
input_size = env.observation_space.n
output_size = env.action_space.n
dis=.99
num_episodes=2000


model = tf.keras.Sequential([
    tf.keras.layers.Dense(output_size, input_shape=[input_size],
                         kernel_initializer=tf.random_uniform_initializer(minval=0, maxval=0.01))
])
model.compile(optimizer=tf.train.GradientDescentOptimizer(learning_rate=learning_rate), loss='mse')
model.summary()


rList=[]
for i in range(num_episodes):
    s = env.reset()
    e = 1.0 / ((i/50)+10)
    rAll = 0
    done = False

    while not done:
        Qs = model.predict(one_hot(s))
        if np.random.rand(1) < e:
            a = env.action_space.sample()
        else:
            a = np.argmax(Qs)

        s1, reward, done, _ = env.step(a)
        if done:
            Qs[0, a] = reward
        else:
            Qs1 = model.predict(one_hot(s1))
            Qs[0, a] = reward + dis*np.max(Qs1)

        model.fit(x=one_hot(s), y=Qs)

        rAll += reward
        s= s1

    rList.append(rAll)

print("Percent of successful episode: "+str(sum(rList)/num_episodes)+"%")
plt.bar(range(len(rList)), rList, color='blue')
plt.show()

2. Tensorflow 2.X Ver2

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
import gym
import matplotlib.pyplot as plt



def SumSqureError(y_true, y_pred):
    return tf.reduce_sum( tf.square(y_true - y_pred) )


def my_init(shape, dtype=None):
    return np.random.uniform(0, 0.01, shape)



env = gym.make("FrozenLake-v1")
INPUT_ONE_HOT = np.identity(env.observation_space.n)

model = keras.Sequential()
model.add(layers.Dense(env.action_space.n, input_shape=(None, env.observation_space.n), kernel_initializer=my_init))
model.summary()
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.1), loss=SumSqureError, metrics=['accuracy'])


dis = 0.99
episodes = 2000
rList = []


def one_hot(x):
    return INPUT_ONE_HOT[x:x + 1]


rAll = 0

for i in range(episodes):
    state = env.reset()

    e = 1.0 / ((i / 50) + 10)
    Done = False

    while not Done :
        Qs = model.predict(one_hot(state))
        
        if np.random.rand(1) < e:
            action = env.action_space.sample()
        else:
            action = np.argmax( Qs )

        new_state, reward, Done, _ = env.step(action)
        #env.render()


        if Done:
            rList.append(reward)
            rAll += reward
            Qs[0,action] = reward
        else :
            Qs[0,action] = reward + dis * np.max(model.predict(one_hot(new_state)))
 
        
        model.fit(one_hot(state), Qs)
        state = new_state

    if (i % 200 == 0) and (i > 0):
        print("Prgress : ", (i/episodes), "  ==> ", (rAll / i))



print("Success rate: " + str(rAll / episodes))
plt.bar(range(len(rList)), rList, color="blue")
plt.show()

env.close()

 

 

2. Tensorflow 1.X

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

tf.disable_v2_behavior()




env = gym.make('FrozenLake-v1')
input_size = env.observation_space.n
output_size = env.action_space.n

episodes = 2000
rAll = 0
rList = []
dis = 0.99
Done = False
ONE_HOT = np.identity(input_size)


X = tf.placeholder(shape=[1, input_size], dtype=tf.float32)
#W = tf.Variable(tf.random_normal([input_size, output_size]))
W = tf.Variable(tf.random_uniform([input_size, output_size], 0, 0.01))
Y = tf.placeholder(shape=[1, output_size], dtype=tf.float32)

Qpred = tf.matmul(X, W)
cost = tf.reduce_sum(tf.square(Y - Qpred))
train = tf.train.GradientDescentOptimizer(learning_rate = 0.1).minimize(cost)

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

def one_hot(x):
    return ONE_HOT[x:x + 1]

for i in range(episodes):
    
    state = env.reset()
    Done = False
    #e = 1. / ((i / 50) + 10)
    e =  1. / ((i / 50) + 10)
    
    while not Done :
        Qs = sess.run(Qpred, feed_dict={X: one_hot(state)})
        
        if np.random.rand(1) < e:
            action = env.action_space.sample()
        else:
            action = np.argmax(Qs)
            
        new_state, reward, Done, _ = env.step(action)
        #env.render()
        
        if Done:
            rAll += reward
            rList.append(reward)
            # Update Q, and no Qs+1, since it's a terminal state
            Qs[0, action] = reward
        else:
            # Obtain the Q_s1 values by feeding the new state through our
            # network
            Qs1 = sess.run(Qpred, feed_dict={X: one_hot(new_state)})
            # Update Q
            Qs[0, action] = reward + dis * np.max(Qs1)
            
        sess.run(train, feed_dict={X: one_hot(state), Y: Qs})
        state = new_state
    
    if (i % 200 == 0) and (i > 0):
        print("Prgress : ", (i/episodes), "  ==> ", (rAll / i))

print("Percent of success of episodes : ", (rAll / episodes))
plt.bar(range(len(rList)), rList, color="blue")
plt.show()

env.close()

https://www.youtube.com/watch?v=ZYX0FaqUeN4 

import numpy as np

t = np.array([[[0,1,2], [3,4,5]], [[6,7,8],[9,10,11]]])
print(t)
print("shape=",t.shape)
print("----------------------")
print("reshape#1")
ar = np.reshape(t, (-1,3))
print(ar)
print("shape=",ar.shape)
print("----------------------")
print("reshape#2")
ar = np.reshape(ar, (-1,1,3))
print(ar)
print("shape=",ar.shape)
print("----------------------")
print("squeeze")
ar = np.squeeze([[0],[1],[2],[3]])
print( ar )
print( "shape=",ar.shape )
print("----------------------")
print("expand_dims")
ar = np.expand_dims([0, 1, 2], 1)
print( ar )
print( "shape=",ar.shape )
In [1]: 
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]]
shape= (2, 2, 3)
----------------------
reshape#1
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
shape= (4, 3)
----------------------
reshape#2
[[[ 0  1  2]]

 [[ 3  4  5]]

 [[ 6  7  8]]

 [[ 9 10 11]]]
shape= (4, 1, 3)
----------------------
squeeze
[0 1 2 3]
shape= (4,)
----------------------
expand_dims
[[0]
 [1]
 [2]]
shape= (3, 1)

 

 

 

클릭 2번이면.....

 

크롬에서 테스트 했습니다.

Microsoft edge에서는 안됩니다.

 

 

1. 메모장에 아래 내용을 복사해서 붙여 넣으세요

javascript:javascript:function testfor() { var url = "https://couponview.netmarble.com/coupon/enn/1384"; if( document.location.href!=url) { document.location.href=url; return; } var elem=document.getElementById("ip_cunpon2"); elem.value="제2의나라 회원번호를 입력하세요";} testfor();

 

2. 게임에서 회원번호를 복사하세요

 

3. 회원번호를 메모장에 붙여넣기 하세요.

 

4. 전체 선택해서 복사하세요. (복사만 해 놓으세요)

 

5. 크롬에서 아무 사이트나 바로가기 창에 바로가기를 만듭니다.

 

 

6. 바로가기 편집해서 붙여넣기 하세요.

 

 

7. Test해 봅니다. 2번 클릭 !!

    1. 주소창에 아무거나 입력

 

    2. 방금 생성 바로가기 클릭

    3. 한번 더 클릭

 

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


sizeof_x = 784
nb_classes = 10
nb_branch = 256
epoch = 15
batch_size = 100
learning_rate=0.001
alg = 0
val_keep_prob = 1.0

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
print( "x_train.shape=", x_train.shape )
print( "x_train.shape=", x_train.shape[0] )

num_iterations = int(x_train.shape[0] / batch_size)

x_train = x_train.reshape(x_train.shape[0], -1).astype('float32') / 255
x_test = x_test.reshape(x_test.shape[0], -1).astype('float32') / 255
print( "x_train.shape=", x_train.shape )
print( "x_test.shape=", x_test.shape )

y_train = tf.keras.utils.to_categorical(y_train, nb_classes)
y_test = tf.keras.utils.to_categorical(y_test, nb_classes)

print( "y_train.shape=", y_train.shape )
print( "y_test.shape=", y_test.shape )


model = tf.keras.Sequential()

model.add(tf.keras.layers.Dense(nb_classes, activation="softmax"))
model.compile(optimizer='adam', loss=tf.keras.losses.categorical_crossentropy, metrics=['accuracy'])

print( "Now training..." )
model.fit(x=x_train, y=y_train, verbose=1, epochs = epoch, batch_size=batch_size)



print( "Now evaluating..." )
result = model.predict(x_test)

v_result = np.argmax(result, 1)
v_y_test= np.argmax(y_test,1)

is_correct = np.equal(v_result, v_y_test).astype('float32')
accuracy = np.mean(is_correct)
print( "accuracy=", accuracy )

for i in range(100):
    r = random.randint(0, x_test.shape[0] - 1)
    image= x_test[r:r+1]
    predict = v_result[r:r+1]
    label = v_y_test[r:r+1]
    if label != predict :
      print("{} {} Label={} Predict={}".format(i, label==predict, label, predict))
      plt.imshow(image.reshape(28, 28),        cmap="Greys",
          interpolation="nearest"
          )
      plt.show()

여기서 스크랩 해 왔습니다.

https://curiousseed.tistory.com/40

 

C#에서 tensorflow 사용하는 방법 알아보기

(*아래 사이트를 참고하여 작성하였습니다: (1) http://euhyeji.blogspot.com/2018/08/tensorflowsharp01.html (2) https://github.com/migueldeicaza/TensorFlowSharp) C#에서 Tensorflow로 만든 모델을 활용할..

curiousseed.tistory.com

 

C#에서 Tensorflow로 만든 모델을 활용할 수 있는 방법은 아래와 같습니다.

Tensorflow에서 제공하는 TensorFlowsharp(https://github.com/migueldeicaza/TensorFlowSharp )을 사용하면 C#에서 tensorflow를 사용할 수 있습니다.

Tensorflow, Keras로 학습시킨 모델을 .NET에 로드시켜 학습이나 참조를 시키는 응용 프로그램을 만들 수 있는 API TensorFlowSharp에서 제공합니다.

TensorFlowSharp C#에서 설치하는 방법은 아래와 같습니다.

 

        <TensorFlowSharp C#에서 설치하는 방법>

        1.        프로젝트 파일을 생성할  .NET Framework 4.6.1 이상으로 설정합니다.
        2.       [project]  [Manage NuGet Packages]  Browse에서 search Tensorflowsharp을 입력합니다. → 
                 TensorFlowSharp을 선택하여 현재 프로젝트에 설치합니다.
        3.       Solution explorer에서 References 보면 TensorFlowSharp 설치되어 있는 것을 확인할  있습니다.

        (참고 사이트:  http://euhyeji.blogspot.com/2018/08/visualstudio2017.html )



 

TensorFlowSharp에서는 두 가지 방식을 지원합니다.

(1) 이미 Tensorflow에서 만들어져 있는 모델을 가져오는 것입니다.

(2) TensorFlow의 문법을 C#에서 사용하는 방식입니다. 아래는 (1), (2)에 대한 각각의 설명입니다.

 

 

1.    이미 Tensorflow에서 만들어져 있는 모델을 가져오는 방식 
       Python에서 TensorFlow 또는 Keras 사용하여 프로토 타입을 생성한 다음 학습된 모델을 저장  다음 TensorFlowSharp 사용하여 .NET 결과를 로드할  있다. 그리고나서 가져온 모델을 가지고 C#에서 자체적으로 데이터를 학습 또는 피드할  있습니다.

 

<TensorFlowSharp Github에 있는 예제 코드>

(참고사이트: https://github.com/migueldeicaza/TensorFlowSharp)  

 

 

2.    TensorFlow의 문법을 C#에서 사용하는 방식 

        : 핵심은 TFSession()을 객체로 선언하고 C#에서 API를 사용하는 방식으로 TensorFlow 문법을 C#에서 사용하는 것입니다. 이것보다는 1번 방식으로 프로젝트를 진행해야 하지않을까 싶습니다.

 

<TensorFlowSharp Github에 있는 예제 코드>

(참고사이트: https://github.com/migueldeicaza/TensorFlowSharp)  

본 게시글은 "홍정모"님의 블로그 게시글을 참고해서 제작하였습니다.

(blog.naver.com/atelierjpro/220965203959)

 

Tensorflow를 C++에서 돌리고 싶을 때를 위해 미리 테스트를 했다.

Windows10 + Visual Studio 2017 (VC14.1)로 테스트를 했다.

Python 3.7 + tensorflow 2.2 버전이다.

boost는 1.73.0 버전에 python numpy 포함해서 직접 컴파일 하였다.

 

 

// ConsoleApplication1.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#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>
#include <boost/thread.hpp>
#include <boost/python/extract.hpp>


namespace py = boost::python;
namespace np = boost::python::numpy;

using namespace boost::python;
using namespace boost::python::numpy;

#define BOOST_ERROR(msg) ( ::boost::detail::error_impl(msg, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION) )


class MyTest
{
public:
	typedef boost::thread THREAD, *pTHREAD;

	int a_;

	MyTest(int a)
		: a_(a)
	{
	}

	int get()
	{
		return a_;
	}

	void set(int _a)
	{
		a_ = _a;
	}

	void threadjob(int tid)
	{
		std::cout << "Thread working! " << tid << std::endl;
	}

	void threadingtest()
	{
		const int num_threads_ = 10;
		pTHREAD *thread_list_;
		thread_list_ = new pTHREAD[num_threads_];
		for (int i = 0; i < num_threads_; i++) thread_list_[i] = 0;

		for (unsigned int thread_id = 0; thread_id < num_threads_; thread_id++)
			thread_list_[thread_id] = new THREAD(&MyTest::threadjob, this, thread_id);

		for (int i = 0; i < num_threads_; i++) thread_list_[i]->join();
	}

	void count()
	{
		a_++;

		std::cout << "A count " << std::endl;
	}

	void getArray(np::ndarray& np_array)
	{
		std::cout << "get array c++" << std::endl;

		double* ddd = (double*)np_array.get_data();

		std::cout << ddd[0] << std::endl;
		std::cout << ddd[1] << std::endl;
		std::cout << ddd[2] << std::endl;
	}

	void setArray(boost::python::numpy::ndarray data) {
		// Access a built-in type (an array)
		boost::python::numpy::ndarray a = data;
		// Need to <extract> array elements because their type is unknown
		std::cout << "First array item: " << extract<int>(a[0]) << std::endl;
	}

	void setPointer(double* ptr)
	{
		std::cout << "pointer " << ptr << std::endl;
	}

	void set_first_element(numpy::ndarray& y, float value)
	{
		y[0] = value;
	}

	void greet(boost::python::object& obj)
	{
		std::cout << "Greet C++" << std::endl;

		PyObject* pobj = obj.ptr();

		static Py_buffer pybuf;

		if (PyObject_GetBuffer(pobj, &pybuf, PyBUF_SIMPLE) != -1)
		{
			void *buf = pybuf.buf;
			double *p = (double*)buf;

			*p += 4.123;
			*(p + 1) += 5.12312;

			//PyBuffer_Release(&pybuf);
		}
	}

	void plusOne(np::ndarray& np_array)
	{
		std::cout << "get array c++" << std::endl;
		double* ddd = (double*)np_array.get_data();
		ddd[0] += 1.0;
	}
};


BOOST_PYTHON_MODULE(my_test)
{
	class_<MyTest>("MyTest", init<int>())
		.def("get", &MyTest::get)
		.def("threadingtest", &MyTest::threadingtest)
		.def("count", &MyTest::count)
		.def("setArray", &MyTest::setArray)
		.def("setPointer", &MyTest::setPointer)
		.def("set_first_element", &MyTest::set_first_element)
		.def("greet", &MyTest::greet)
		.def("getArray", &MyTest::getArray)
		.def("plusOne", &MyTest::plusOne)
		.add_property("value", &MyTest::get, &MyTest::set);
}



static const char * pycode = "import my_test\n"
"import numpy as np\n"
"import tensorflow.compat.v1 as tf\n"
"tf.disable_v2_behavior()\n"
"mt = my_test.MyTest(123)\n"
"mt.count()\n"
"print(mt.get())\n"
"\n"
"print(mt.value)\n"
"\n"
"mt.value = 12345\n"
"\n"
"print(mt.value)\n"
"\n"
"mt.threadingtest()\n"
"\n"
"b = np.array([10.0, 20.0, 30.0], dtype = np.float)\n"
"print(b)\n"
"mt.greet(b)\n"
"print(b)\n"
"mt.greet(b)\n"
"print(b)\n"
"mt.getArray(b)\n"
"#mt.setArray(b)\n"
"#my_arr = array('f', [1, 2, 3, 4, 5])\n"
"#mt.set_first_element(b.array, 1123.0)\n"
"#mt.setPointer(b.data)\n"
"\n"
"input1 = tf.placeholder(tf.float32)\n"
"input2 = tf.placeholder(tf.float32)\n"
"output = tf.multiply(input1, input2)\n"
"\n"
"x_input = np.array([2], dtype = np.float)\n"
"y_input = np.array([3], dtype = np.float)\n"
"\n"
"with tf.Session() as sess :\n"
"	print(\"Hello !\")\n"
"	print(sess.run([output], feed_dict = { input1:x_input, input2 : y_input }))\n"
"\n"
"mt.plusOne(x_input)\n"
"mt.plusOne(y_input)\n"
"\n"
"print(x_input)\n"
"print(y_input)\n"
"\n"
"with tf.Session() as sess :\n"
"	print(\"Hello !\")\n"
"	print(sess.run([output], feed_dict = { input1:x_input, input2 : y_input }))";
















void exec_test()
{
	// Retrieve the main module
	py::object main = py::import("__main__");

	// Retrieve the main module's namespace
	py::object global(main.attr("__dict__"));

	py::object result = py::exec(pycode,
		global, global);

	py::object print = py::import("__main__").attr("__builtins__").attr("print");
	print(result);
}




int main()
{
	using namespace std;
	//MyTest my_test(0);

	// 본인의 상황에 맞게 설정한다.
	// 나는 아나콘다 가상환경을 만들지 않았다.
	Py_SetPythonHome(L"C:\\ProgramData\\Anaconda3");

	// my_test 핸들러들을 파이썬에 등록한다.
	// Py_Initialize() 함수보다 먼저 와야한다.
	if (PyImport_AppendInittab("my_test", &PyInit_my_test) == -1)
		throw std::runtime_error("Failed to add embedded_hello to the interpreter's "
			"builtin modules");

	Py_Initialize();
	np::initialize();

	if (py::handle_exception(exec_test))
	{
		if (PyErr_Occurred())
		{
			printf("Python Error detected");
			PyErr_Print();
		}
		else
		{
			printf("A C++ exception was thrown  for which "
				"there was no exception translator registered.");
		}
	}

	return 0;
}

 

 

 

위의 소스를 실행하면 아래와 같은 결과를 보게 된다.

+ Recent posts