import tensorflow as tf
print("TensorFlow version: {}".format(tf.VERSION))
TensorFlow version: 1.11.0
numpy
짜듯이 짤 수 있음a
를 출력하면 계산된 값이 나오지 않음a = tf.add(3, 5)
print(a)
Tensor("Add:0", shape=(), dtype=int32)
tf.Session()
을 실행하여 계산함tf.Session()
을 열면 TF default로 GPU 메모리를 다 잡아버림gpu_options
을 다음과 같이 준다nvidia-smi
watch
라는 명령어와 함께 쓰면 계속 갱신하면서 메모리 변화를 볼 수 있음watch -n 1 nvidia-smi
sess_config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))
#sess = tf.Session()
sess = tf.Session(config=sess_config)
print(sess.run(a))
sess.close()
8
tf.Session()
을 with
구문으로¶session
을 열면 sess.close()
로 명시적으로 닫아줘야 한다.with
구문이 끝나면 알아서 session
이 닫힌다.with tf.Session(config=sess_config) as sess:
print(sess.run(a))
8
with tf.Session()
구문 안에서는 sess.run()
대신 eval()
을 쓸 수 있다¶with tf.Session(config=sess_config) as sess:
print(a.eval())
8
tf.InteractiveSession()
¶tf.InteractiveSession()
에서는 세션 객체를 계속 참조하지 않고 값을 볼 수 있다.
sess = tf.InteractiveSession(config=sess_config)
print(a.eval())
8
x = 2
y = 3
w = tf.add(x, y)
z = tf.multiply(x, y)
p = tf.pow(z, w)
print(p)
with tf.Session(config=sess_config) as sess:
print(sess.run(p))
Tensor("Pow:0", shape=(), dtype=int32) 7776
Tensor
변수와 일반 python
변수¶import numpy as np
x = 2
y = 3
w = x + y
z = x * y
p = np.power(z, w)
print(p)
with tf.Session(config=sess_config) as sess:
print(sess.run(p)) # p는 sess.run()에 넣는 Tensor가 아니고 일반 python 변수이기 때문에 에러가 난다
7776
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn) 283 self._unique_fetches.append(ops.get_default_graph().as_graph_element( --> 284 fetch, allow_tensor=True, allow_operation=True)) 285 except TypeError as e: /usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation) 3487 with self._lock: -> 3488 return self._as_graph_element_locked(obj, allow_tensor, allow_operation) 3489 /usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation) 3576 raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__, -> 3577 types_str)) 3578 TypeError: Can not convert a int64 into a Tensor or Operation. During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-9-43fce4ac04f5> in <module>() 8 print(p) 9 with tf.Session(config=sess_config) as sess: ---> 10 print(sess.run(p)) # p는 sess.run()에 넣는 Tensor가 아니고 일반 python 변수이기 때문에 에러가 난다 /usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata) 885 try: 886 result = self._run(None, fetches, feed_dict, options_ptr, --> 887 run_metadata_ptr) 888 if run_metadata: 889 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) /usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 1093 # Create a fetch handler to take care of the structure of fetches. 1094 fetch_handler = _FetchHandler( -> 1095 self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles) 1096 1097 # Run request and get response. /usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, graph, fetches, feeds, feed_handles) 427 """ 428 with graph.as_default(): --> 429 self._fetch_mapper = _FetchMapper.for_fetch(fetches) 430 self._fetches = [] 431 self._targets = [] /usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py in for_fetch(fetch) 253 if isinstance(fetch, tensor_type): 254 fetches, contraction_fn = fetch_fn(fetch) --> 255 return _ElementFetchMapper(fetches, contraction_fn) 256 # Did not find anything. 257 raise TypeError('Fetch argument %r has invalid type %r' % (fetch, /usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn) 286 raise TypeError('Fetch argument %r has invalid type %r, ' 287 'must be a string or Tensor. (%s)' % --> 288 (fetch, type(fetch), str(e))) 289 except ValueError as e: 290 raise ValueError('Fetch argument %r cannot be interpreted as a ' TypeError: Fetch argument 7776 has invalid type <class 'numpy.int64'>, must be a string or Tensor. (Can not convert a int64 into a Tensor or Operation.)
x = tf.constant(2)
y = tf.constant(3)
w = x + y
z = x * y
p = tf.pow(z, w)
print(p)
with tf.Session(config=sess_config) as sess:
print(sess.run(p))
Tensor("Pow_1:0", shape=(), dtype=int32) 7776
x = 3
y = 5
z = 4
w = 6
# TODO
# only tf.multiply
p = tf.multiply(x, y) + tf.multiply(z, w)
# both tf.multiply and tf.add
q = tf.add(tf.multiply(x, y), tf.multiply(z, w))
with tf.Session() as sess:
print(sess.run(p))
print(sess.run(q))
39 39
tf.convert_to_tensor
: list -> tensortf.matmul
사용tf.squeeze
사용# TODO
x = tf.convert_to_tensor([[3, 4]])
y = tf.convert_to_tensor([[5], [6]])
# tf.matmul and tf.squeeze
z = tf.squeeze(tf.matmul(x, y))
#z = tf.matmul(x, y)
with tf.Session() as sess:
print(sess.run(z))
39