Skip to content

Commit 4524d2e

Browse files
committed
hello world
1 parent 09f0521 commit 4524d2e

22 files changed

+8479
-0
lines changed
Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"https://codeonweb.com/entry/5f15bf8e-d704-49e0-909a-db4450433b74"
8+
]
9+
},
10+
{
11+
"cell_type": "code",
12+
"execution_count": 1,
13+
"metadata": {
14+
"collapsed": true
15+
},
16+
"outputs": [],
17+
"source": [
18+
"import tensorflow as tf\n",
19+
"\n",
20+
"# 1x2 형렬을 만드는 Constant 연산을 생성합니다.\n",
21+
"# 이 연산자는 기본 그래프의 노드로 추가됩니다.\n",
22+
"#\n",
23+
"# 생성자에 의해 반환된 값(matrix1)은 Constant 연산의 출력을 나타냅니다.\n",
24+
"matrix1 = tf.constant([[3., 3.]])\n",
25+
"\n",
26+
"# 2x1 행렬을 만드는 또 다른 Constant를 생성합니다.\n",
27+
"matrix2 = tf.constant([[2.],[2.]])\n",
28+
"\n",
29+
"# 'matrix1'과 'matrix2'를 입력으로 받는 Matmul 연산을 생성합니다.\n",
30+
"# 반환값인 'product'는 행렬을 곱한 결과를 나타냅니다.\n",
31+
"product = tf.matmul(matrix1, matrix2)"
32+
]
33+
},
34+
{
35+
"cell_type": "code",
36+
"execution_count": 2,
37+
"metadata": {
38+
"collapsed": false,
39+
"scrolled": true
40+
},
41+
"outputs": [
42+
{
43+
"name": "stdout",
44+
"output_type": "stream",
45+
"text": [
46+
"[[ 12.]]\n"
47+
]
48+
}
49+
],
50+
"source": [
51+
"import tensorflow as tf\n",
52+
"# 기본 그래프로 세션을 생성.\n",
53+
"sess = tf.Session()\n",
54+
"\n",
55+
"# matmul 연산을 실행하려면 matmul 연산의 출력을 나타내는 'product'를\n",
56+
"# 인자로 넘겨주면서 세션의 'run()' 메소드를 호출합니다. 이렇게 호출하면\n",
57+
"# matmul 연산의 출력을 다시 얻고 싶다는 뜻입니다.\n",
58+
"#\n",
59+
"# 연산이 필요로 하는 모든 입력은 세션에 의해 자동으로 실행됩니다.\n",
60+
"# 일반적으로 병렬적으로 실행되지요.\n",
61+
"#\n",
62+
"# 따라서 'run(product)' 호출은 그래프 내의 세 개 연산을 실행하게 됩니다.\n",
63+
"# 두 개의 상수와 matmul이 바로 그 연산이지요.\n",
64+
"#\n",
65+
"# 연산의 출력은 'result'에 numpy의 `ndarray` 객체 형태로 저장됩니다. \n",
66+
"result = sess.run(product)\n",
67+
"print(result)\n",
68+
"# ==> [[ 12.]]\n",
69+
"\n",
70+
"# 다 끝났으면 세션을 닫아줍니다.\n",
71+
"sess.close()"
72+
]
73+
},
74+
{
75+
"cell_type": "code",
76+
"execution_count": 3,
77+
"metadata": {
78+
"collapsed": false
79+
},
80+
"outputs": [
81+
{
82+
"name": "stdout",
83+
"output_type": "stream",
84+
"text": [
85+
"[array([[ 12.]], dtype=float32)]\n"
86+
]
87+
}
88+
],
89+
"source": [
90+
"with tf.Session() as sess:\n",
91+
" result = sess.run([product])\n",
92+
" print(result)"
93+
]
94+
},
95+
{
96+
"cell_type": "code",
97+
"execution_count": 4,
98+
"metadata": {
99+
"collapsed": true
100+
},
101+
"outputs": [],
102+
"source": [
103+
"with tf.Session() as sess:\n",
104+
" with tf.device(\"/gpu:1\"):\n",
105+
" matrix1 = tf.constant([[3., 3.]])\n",
106+
" matrix2 = tf.constant([[2.],[2.]])\n",
107+
" product = tf.matmul(matrix1, matrix2)"
108+
]
109+
},
110+
{
111+
"cell_type": "markdown",
112+
"metadata": {},
113+
"source": [
114+
"대화형으로 사용(Interactive Usage)\n",
115+
"\n",
116+
"이 문서에서 본 파이썬 예제에서는 그래프를 Session에 올린 뒤 Session.run() 메소드를 이용해 연산을 실행했습니다.\n",
117+
"\n",
118+
"IPython과 같은 대화형 파이썬 환경에서 보다 쉽게 사용하려면,InteractiveSession 클래스를 통해 Tensor.eval()과 Operation.run() 메소드를 호출할 수도 있습니다. 그러면 세션을 위해 변수를 미리 생성할 필요가 없습니다."
119+
]
120+
},
121+
{
122+
"cell_type": "code",
123+
"execution_count": null,
124+
"metadata": {
125+
"collapsed": true
126+
},
127+
"outputs": [],
128+
"source": [
129+
"# 대화형 TensorFlow 세션에 들어갑니다.\n",
130+
"import tensorflow as tf\n",
131+
"sess = tf.InteractiveSession()\n",
132+
"\n",
133+
"x = tf.Variable([1.0, 2.0])\n",
134+
"a = tf.constant([3.0, 3.0])\n",
135+
"\n",
136+
"# 'x'의 초기화 연산의 run() 메소드를 사용해서 'x'를 초기화합니다.\n",
137+
"x.initializer.run()\n",
138+
"\n",
139+
"# 'x'에서 'a'를 빼기 위해 연산을 추가. 실행하고 결과를 출력합니다.\n",
140+
"sub = tf.sub(x, a)\n",
141+
"print(sub.eval())\n",
142+
"# ==> [-2. -1.]\n",
143+
"\n",
144+
"# 다 끝났으면 세션을 닫아줍니다.\n",
145+
"sess.close()"
146+
]
147+
},
148+
{
149+
"cell_type": "markdown",
150+
"metadata": {},
151+
"source": [
152+
"텐서\n",
153+
"\n",
154+
"TensorFlow 프로그램은 텐서(tensor) 데이터 구조를 사용해서 모든 데이터를 나타냅니다. 계산 그래프에서 연산을 할 때에도 오직 텐서만 주고 받습니다. TensorFlow의 텐서는 n 차원의 배열이나 리스트라고 생각하면 됩니다. 텐서는 정적 타입(static type), 랭크(rank), 모양(shape)의 속성을 가집니다. TensorFlow가 어떻게 이 개념들을 다루는지 알고 싶다면 Rank, Shape, and Type 문서를 참고하십시오.\n",
155+
"\n",
156+
"변수\n",
157+
"\n",
158+
"변수는 그래프가 실행되는 동안 어떤 상태를 담고 있습니다. 다음 예제는 간단한 계수 역할을 하는 변수를 보여주고 있습니다. 더 자세한 사항은 Variables를 참고하세요."
159+
]
160+
},
161+
{
162+
"cell_type": "code",
163+
"execution_count": 5,
164+
"metadata": {
165+
"collapsed": false,
166+
"scrolled": true
167+
},
168+
"outputs": [
169+
{
170+
"name": "stdout",
171+
"output_type": "stream",
172+
"text": [
173+
"0\n",
174+
"1\n",
175+
"2\n",
176+
"3\n"
177+
]
178+
}
179+
],
180+
"source": [
181+
"import tensorflow as tf\n",
182+
"# 변수를 하나 생성하고 스칼라 값인 0으로 초기화합니다.\n",
183+
"state = tf.Variable(0, name=\"counter\")\n",
184+
"\n",
185+
"# one을 state에 더하는 연산을 생성합니다.\n",
186+
"one = tf.constant(1)\n",
187+
"new_value = tf.add(state, one)\n",
188+
"update = tf.assign(state, new_value)\n",
189+
"\n",
190+
"# 변수는 그래프가 올라간 뒤 'init' 연산을 실행해서 반드시 초기화 되어야 합니다.\n",
191+
"# 그 전에 먼저 'init' 연산을 그래프에 추가해야 합니다.\n",
192+
"init_op = tf.initialize_all_variables()\n",
193+
"\n",
194+
"# 그래프를 올리고 연산을 실행합니다.\n",
195+
"with tf.Session() as sess:\n",
196+
" # 'init' 연산을 실행합니다.\n",
197+
" sess.run(init_op)\n",
198+
" # 'state'의 초기값을 출력합니다.\n",
199+
" print(sess.run(state))\n",
200+
" # 'state'를 갱신하는 연산을 실행하고 'state'를 출력합니다.\n",
201+
" for _ in range(3):\n",
202+
" sess.run(update)\n",
203+
" print(sess.run(state))\n"
204+
]
205+
},
206+
{
207+
"cell_type": "markdown",
208+
"metadata": {},
209+
"source": [
210+
"이 코드에 등장한 assign() 연산은 add() 연산과 마찬가지로 표현 그래프(expression graph)의 일종입니다. 그래서 run()으로 그 표현을 실행하기 전에는 실제 대입 연산을 수행하지 않습니다.\n",
211+
"\n",
212+
"일반적으로 통계 모델의 파라미터를 변수로 나타냅니다. 예를 들어, 신경망의 가중치(weight)를 텐서 변수에 저장할 수 있습니다. 훈련 과정이 진행되면 훈련 그래프를 반복적으로 실행해서 이 텐서를 갱신하게 됩니다.\n",
213+
"\n"
214+
]
215+
},
216+
{
217+
"cell_type": "markdown",
218+
"metadata": {},
219+
"source": [
220+
"가져오기(Fetches)\n",
221+
"\n",
222+
"연산의 출력을 가져오기 위해서는 Session 객체에서 가져오고 싶은 텐서를 run()에 인자로 넘겨서 그래프를 실행해야 합니다. 이전 예제에서 우리는 state라는 한 개의 노드를 가져왔지요. 하지만 여러 개의 텐서를 가져올 수도 있습니다:"
223+
]
224+
},
225+
{
226+
"cell_type": "code",
227+
"execution_count": 11,
228+
"metadata": {
229+
"collapsed": false
230+
},
231+
"outputs": [
232+
{
233+
"name": "stdout",
234+
"output_type": "stream",
235+
"text": [
236+
"[21.0, 7.0]\n"
237+
]
238+
}
239+
],
240+
"source": [
241+
"import tensorflow as tf\n",
242+
"\n",
243+
"input1 = tf.constant(3.0)\n",
244+
"input2 = tf.constant(2.0)\n",
245+
"input3 = tf.constant(5.0)\n",
246+
"intermed = tf.add(input2, input3)\n",
247+
"mul = tf.mul(input1, intermed)\n",
248+
"\n",
249+
"with tf.Session() as sess:\n",
250+
" result = sess.run([mul, intermed])\n",
251+
" print(result)\n",
252+
" \n",
253+
"#요청된 텐서들의 출력값을 만드는 데 관여하는 모든 연산은 \n",
254+
"#(요청된 텐서 하나 당 한 번이 아니라) 한 번만 실행됩니다."
255+
]
256+
},
257+
{
258+
"cell_type": "markdown",
259+
"metadata": {},
260+
"source": [
261+
"피드(Feeds)\n",
262+
"\n",
263+
"지금까지 본 예제에서는 텐서의 값을 Conatants와 Variables에 미리 저장한 뒤 계산 그래프에 넘겨줍니다. TensorFlow는 그래프 내에서 직접 텐서의 값을 할당할 수 있는 방법도 제공하고 있습니다.\n",
264+
"\n",
265+
"피드(feed)는 연산의 출력을 지정한 텐서 값으로 임시 대체합니다. 임시로 사용할 피드 데이터는 run()의 인자로 넘겨줄 수 있습니다. 피드 데이터는 run을 호출할 때 명시적 인자로 넘겨질 때만 사용됩니다. 가장 흔한 사용법은 tf.placeholder()를 사용해 특정 연산을 \"피드\" 연산으로 지정하는 것입니다."
266+
]
267+
},
268+
{
269+
"cell_type": "code",
270+
"execution_count": 12,
271+
"metadata": {
272+
"collapsed": false
273+
},
274+
"outputs": [
275+
{
276+
"name": "stdout",
277+
"output_type": "stream",
278+
"text": [
279+
"[array([ 14.], dtype=float32)]\n"
280+
]
281+
}
282+
],
283+
"source": [
284+
"import tensorflow as tf\n",
285+
"\n",
286+
"input1 = tf.placeholder(tf.float32)\n",
287+
"input2 = tf.placeholder(tf.float32)\n",
288+
"output = tf.mul(input1, input2)\n",
289+
"\n",
290+
"with tf.Session() as sess:\n",
291+
" print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))\n",
292+
"\n",
293+
"# output:\n",
294+
"# [array([ 14.], dtype=float32)]"
295+
]
296+
}
297+
],
298+
"metadata": {
299+
"kernelspec": {
300+
"display_name": "Python 2",
301+
"language": "python",
302+
"name": "python2"
303+
},
304+
"language_info": {
305+
"codemirror_mode": {
306+
"name": "ipython",
307+
"version": 2
308+
},
309+
"file_extension": ".py",
310+
"mimetype": "text/x-python",
311+
"name": "python",
312+
"nbconvert_exporter": "python",
313+
"pygments_lexer": "ipython2",
314+
"version": "2.7.11"
315+
}
316+
},
317+
"nbformat": 4,
318+
"nbformat_minor": 0
319+
}

0 commit comments

Comments
 (0)