[API] TensorBoard: Usage


5 steps of using TensorBoard

1.   From TF graph, decide which tensors you want to log

with tf.variable_scope('layer1') as scope:

tf.summary.image('input', x_image, 3)

tf.summary.histogram("layer", L1)

tf.summary.scalar("loss", cost)

2.     Merge all summaries

summary = tf.summary.merge_all()

3.     Create writer and add graph

# Create summary writer

writer = tf.summary.FileWriter(TB_SUMMARY_DIR)

writer.add_graph(sess.graph)

4.     Run summary merge and add_summary

s, _ = sess.run([summary, optimizer], feed_dict=feed_dict)

writer.add_summary(s, global_step=global_step)

5.     Launch TensorBoard

tensorboard --logdir=/tmp/mnist_logs

 

The Visualizations

1.     From TF graph, decide which tensors you want to log

Image Input

# Image input

x_image = tf.reshape(X, [-1, 28, 28, 1])

tf.summary.image('input', x_image, 3)

 

W209 一 OSual


Histogram (multi-dimensional tensors) 

with tf.variable_scope('layer1') as scope:

   W1 = tf.get_variable("W", shape=[784, 512])

   b1 = tf.Variable(tf.random_normal([512]))

   L1 = tf.nn.relu(tf.matmul(X, W1) + b1)

   L1 = tf.nn.dropout(L1, keep_prob=keep_prob)

   tf.summary.histogram("X", X)

   tf.summary.histogram("weights", W1)

   tf.summary.histogram("bias", b1)

   tf.summary.histogram("layer", L1)

 

layer2/layer 
layer2/weights

Scalar tensors

tf.summary.scalar("loss", cost)


 

Add scope for better hierarchy

with tf.variable_scope('layer1') as scope:

  W1 = tf.get_variable("W", shape=[784, 512],...

  b1 = tf.Variable(tf.random_normal([512]))

  L1 = tf.nn.relu(tf.matmul(X, W1) + b1)

  L1 = tf.nn.dropout(L1, keep_prob=keep_prob)

  tf.summary.histogram("X", X)

  tf.summary.histogram("weights", W1)

  tf.summary.histogram("bias", b1)

  tf.summary.histogram("layer", L1)

with tf.variable_scope('layer2') as scope:

   ...

with tf.variable_scope('layer3') as scope:

   ...

with tf.variable_scope('layer4') as scope:

   ...

with tf.variable_scope('layer5') as scope:


layer2 
layerl

 

2.     Merge summaries and

3.     Create writer after creating session

# Summary

summary = tf.summary.merge_all()

# initialize

sess = tf.Session()

sess.run(tf.global_variables_initializer())

# Create summary writer

writer = tf.summary.FileWriter(TB_SUMMARY_DIR)

writer.add_graph(sess.graph)

 

4.     Run merged summary and write (add summary)

s, _ = sess.run([summary, optimizer], feed_dict=feed_dict)

writer.add_summary(s, global_step=global_step)

global_step += 1

 

5.     Launch tensorboard (local)

$ tensorboard logdir=/tmp/mnist_logs

Starting TensorBoard b'41' on port 6006

(You can navigate to http://127.0.0.1:6006)

 

6.     Multiple runs

tensorboard logdir=/tmp/mnist_logs/run1

writer = tf.summary.FileWriter(/tmp/mnist_logs/run1)

tensorboard logdir=/tmp/mnist_logs/run2

writer = tf.summary.FileWriter(/tmp/mnist_logs/run1)

tensorboard logdir=/tmp/mnist_logs

 

 

이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 "모두를 위한 머신러닝/딥러닝 강의" TensorBoard 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorboard: Visualizaing Learning 

(텐서보드: 학습 시각화)

Tensorboard: Visualizaing Learning

거대한 deep neural network을 학습하는 것처럼 TensorFlow를 사용한 계산은 복잡하고 이해하기 어려울 수 있다. TensorFlow 프로그램을 더 쉽게 이해하고, 디버깅 하고 그리고 최적화 하기위해서, TensorBoard라 부르는 시각화 도구 세트를 포함했다. TensorBoard를 사용하여, TensorFlow 그래프를 시각화 하고, Graph의 실행에 대한 양적지표(quantitative metrics)을 도표로 나타내고, 그리고 그것을 통하여 전달된 이미지와 같은 추가적인 데이터를 보여줄 수 있다. TensorBoard가 완전히 구성되면, 아래와 같이 보일 것이다.

이 튜토리얼은 간단한 TensorBoard 사용법을 담고 있으며 사직 할 수 있도록 돕고자 하는 목적이 있다. 또한 다른 사용 가능한 자원도 있다.  TensorBoard's GitHub는 tips 과 트릭 그리고 디버깅 정보를 포함하는 TensorBoard 사용법에 대한 더 많은 정보를 가지고 있다.

Serializing the data

TensorBoard는 Tensorflow 이벤트 파일을 읽어서 동작한다. Tensorflow 이벤트 파일은 Tensorflow를 수행할 때 생성한 summary 데이터를 포함한다. TensorBoard에는 summary 데이터를 위한 일반적인 라이프사이클이 있다.

첫 번째, summary 데이터를 수집하고 싶은 Tensorflow 그래프를 생성하고, summary operations 에 주석을 달고 싶은 노드를 결정한다.

예를 들어, MNIST 숫자를 인식하기 위해 CNN을 학습한다고 가정한다. 시간에 따라 학습율이 어떻게 달라지는지, 목표 함수가 어떻게 바뀌어가는지 기록하고 싶어할 것이다. 학습율과 손실을 각각 출력하는 노드에 tf.summary.scalar ops을 추가함으로써 데이터를 수집한다. 그러면, scalar_summary에는 'learning rate' 또는 'loss function' 과 같은 의미있는 tag를 제공한다.

아마도 특정 계층의 activations 분포 또는 gradients 또는 weights의 분포를 시각화하고 싶을 수 있다. gradient 결과물이나 가중치를 가지는 변수에 각각 tf.summary.histogram ops를 추가하여 데이터를 수집한다.

사용가능한 모든 summary operation에 대한 자세한 내용은 summary operations 문서를 확인하면 된다.


Tensorflow에서의 Operation은 operation을 수행하거나 결과에 의존성이 있는 operation이 수행 될 때까지 아무것도 하지 않는다. 그리고 방금 생성했던 summary 노드들은  그래프에서 지엽적(주변장치)이다. 현재 수행중인 어떠한 operation도  summary 노드들과 연관성이 있지 않다. 그래서 summaries를 만들기 위해서, 모든 summary 노드들을 수행 할 필요가 있다. 직접 수동으로 모든 summary 노드들을 관리하는 것은 지루한 일이 될 것이다, 그래서 모든 summary 데이터를 생성하는 single operation으로 여러 summary operation을 합치기 위해서 tf.summary.merge_all을 사용하자.

그러면, 주어진 단계에 모든 summary 데이터를 담은 직렬화된 Summary 프로토버프 오브젝트를 생성하는 합쳐진 summary op을 실행시킬 수 있다. 마지막으로, 이러한 summary 데이터를 디스크에 쓰기 위해서, summary 프로토버프를  tf.summary.FileWriter.으로 전달한다.

 FileWriter는 생성자에서 로그디렉토리를 사용해야 한다. - 로그 디렉토리는 꽤 중요하다, 모든 이벤트들이 쓰여질 디렉토리이다. 또한, FileWriter는 생성자에서 Graph를 선택적으로 사용할 수 있다. 그래프 오브젝트를 받으면, Tensorboard는 tensor shape 정보에 때라 Graph를 시각화 할 것이다. Graph를 통하여 어떠한 흐름인지 훨씬 더 나은 정보를 주게 될 것이다.   Tensor shape information.참고

Graph를 수정했고 하나의 FileWriter를 갖게 되었기 때문에, 네트워크를 실행할 준비가 되었다. 원한다면, 합쳐진 summary op를 매 단계마다 실행시키고, 많은 양의 학습데이터를 기록할 수 있다. 그렇지만 필요한 것보다 더 많은 데이터가 될 가능성이 있다. 대신, n 단계 마다 합쳐진 summary op를 수행하도록 고려해보자.

아래의 예제 코드는  simple MNIST tutorial의 수정본이며, 몇 개의 summary ops를 추가하고, 10 단계마다 수행하게 된다. 이것을 수행하고 tensorboard --logdir=/tmp/tensorflow/mnist을 실행하게 되면, 학습이 진행되는 동안 weights 또는 accuracy가 어떻게 변화하는지에 대한 통계들을 시각화 할 수 있다. 아래의 코드는 발췌 된 것이고; 전체 소스는 here.에서 확인

def variable_summaries(var):
 
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
 
with tf.name_scope('summaries'):
    mean
= tf.reduce_mean(var)
    tf
.summary.scalar('mean', mean)
   
with tf.name_scope('stddev'):
      stddev
= tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
    tf
.summary.scalar('stddev', stddev)
    tf
.summary.scalar('max', tf.reduce_max(var))
    tf
.summary.scalar('min', tf.reduce_min(var))
    tf
.summary.histogram('histogram', var)

def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
 
"""Reusable code for making a simple neural net layer.

  It does a matrix multiply, bias add, and then uses relu to nonlinearize.
  It also sets up name scoping so that the resultant graph is easy to read,
  and adds a number of summary ops.
  """

 
# Adding a name scope ensures logical grouping of the layers in the graph.
 
with tf.name_scope(layer_name):
   
# This Variable will hold the state of the weights for the layer
   
with tf.name_scope('weights'):
      weights
= weight_variable([input_dim, output_dim])
      variable_summaries
(weights)
   
with tf.name_scope('biases'):
      biases
= bias_variable([output_dim])
      variable_summaries
(biases)
   
with tf.name_scope('Wx_plus_b'):
      preactivate
= tf.matmul(input_tensor, weights) + biases
      tf
.summary.histogram('pre_activations', preactivate)
    activations
= act(preactivate, name='activation')
    tf
.summary.histogram('activations', activations)
   
return activations

hidden1
= nn_layer(x, 784, 500, 'layer1')

with tf.name_scope('dropout'):
  keep_prob
= tf.placeholder(tf.float32)
  tf
.summary.scalar('dropout_keep_probability', keep_prob)
  dropped
= tf.nn.dropout(hidden1, keep_prob)

# Do not apply softmax activation yet, see below.
y
= nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)

with tf.name_scope('cross_entropy'):
 
# The raw formulation of cross-entropy,
 
#
 
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.softmax(y)),
 
#                               reduction_indices=[1]))
 
#
 
# can be numerically unstable.
 
#
 
# So here we use tf.nn.softmax_cross_entropy_with_logits on the
 
# raw outputs of the nn_layer above, and then average across
 
# the batch.
  diff
= tf.nn.softmax_cross_entropy_with_logits(targets=y_, logits=y)
 
with tf.name_scope('total'):
    cross_entropy
= tf.reduce_mean(diff)
tf
.summary.scalar('cross_entropy', cross_entropy)

with tf.name_scope('train'):
  train_step
= tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(
      cross_entropy
)

with tf.name_scope('accuracy'):
 
with tf.name_scope('correct_prediction'):
    correct_prediction
= tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
 
with tf.name_scope('accuracy'):
    accuracy
= tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf
.summary.scalar('accuracy', accuracy)

# Merge all the summaries and write them out to /tmp/mnist_logs (by default)
merged
= tf.summary.merge_all()
train_writer
= tf.summary.FileWriter(FLAGS.summaries_dir + '/train',
                                      sess
.graph)
test_writer
= tf.summary.FileWriter(FLAGS.summaries_dir + '/test')
tf
.global_variables_initializer().run()

FileWriter를 초기화 시킨 후에, 모델을 train 하거나 test하기 위해서 FileWriter에 summaries을 추가해야 한다.

# Train the model, and also write summaries.
# Every 10th step, measure test-set accuracy, and write test summaries
# All other steps, run train_step on training data, & add training summaries

def feed_dict(train):
 
"""Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""
 
if train or FLAGS.fake_data:
    xs
, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)
    k
= FLAGS.dropout
 
else:
    xs
, ys = mnist.test.images, mnist.test.labels
    k
= 1.0
 
return {x: xs, y_: ys, keep_prob: k}

for i in range(FLAGS.max_steps):
 
if i % 10 == 0:  # Record summaries and test-set accuracy
    summary
, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
    test_writer
.add_summary(summary, i)
   
print('Accuracy at step %s: %s' % (i, acc))
 
else:  # Record train set summaries, and train
    summary
, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
    train_writer
.add_summary(summary, i)

이제 Tensorboard를 사용하여 이러한 데이터를 시각하기 위한 모든 설정이 되었다.

Launching TensorBoard

Tensorboard를 실행하기 위해서,  아래의 명령을 사용한다.(alternatively python -m tensorboard.main)

tensorboard --logdir=path/to/log-directory

logdir은 FileWriter가 데이터를 직렬화 시켜놓은 디렉토리를 가리킨다. logdir 디렉토리가 개별 실행으로부터 직렬화된 데이터를 포함하는 하위 디렉토리들을 포함하면, Tensorboard는 모든 수행으로부터의 데이터를 시각화 할 것이다. Tensorboard가 수행중이라면, Tensorboard를 보기위해 웹 브라우저에서 localhost:6006을 접속하여 볼 수 있다.

Tensorboard를 보면, 오른쪽 상단 구석에서 navigation 탭을 볼 수 있다. 각각의 탭은 시각화 될 수 있는 직렬화된 데이터 셋을 의미한다.

Graph를 시각화하기 위해서, graph 탭을 사용하는 방법에 대한 자세한 내용은  TensorBoard: Graph Visualization. 을 참고하자.

전반적인 Tensorboard에 대한 사용 정보를 알고 싶으면 TensorBoard's GitHub 을 참고하자.


이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 TensorFlow Develop의 TensorBoard 대한 학습노트입니다.


Posted by 이성윤

[API] Tensorflow Control Flow

(텐서플로우 제어 연산자)

Note: Functions taking  Tensor  arguments can also take anything accepted by  tf.convert_to_tensor .


Tensorflow Logical Operators

TensorFlow provides several operations that you can use to add logical operators to your graph.


tf.logical_and(x, y, name=None)


Returns the truth value of x AND y element-wise.

Args:
  • x: A Tensor of type bool.
  • y: A Tensor of type bool.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Logical Operators


Tensorflow tf.logical_and 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.logical_and(tf.cast(const1, tf.bool), tf.cast(const2, tf.bool)))
   ...:     print(str(xs) + " -> " + str(tfutil.get_operation_value(tf.cast(y, tf.int32))))
(0, 0) -> 0
(1, 0) -> 0
(0, 1) -> 0
(1, 1) -> 1


tf.logical_not(x, name=None)


Returns the truth value of NOT x element-wise.

Args:
  • x: A Tensor of type bool.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Logical Operators


Tensorflow tf.logical_not 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [0, 1]:
   ...:     const = tf.constant(xs)
   ...:     y = tfutil.get_operation_value(tf.logical_not(tf.cast(const, tf.bool)))
   ...:     print(str(xs) + " -> " + str(tfutil.get_operation_value(tf.cast(y, tf.int32))))
0 -> 1
1 -> 0

tf.logical_or(x, y, name=None)


Returns the truth value of x OR y element-wise.

Args:
  • x: A Tensor of type bool.
  • y: A Tensor of type bool.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Logical Operators


Tensorflow tf.logical_or 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.logical_or(tf.cast(const1, tf.bool), tf.cast(const2, tf.bool)))
   ...:     print(str(xs) + " -> " + str(tfutil.get_operation_value(tf.cast(y, tf.int32))))
(0, 0) -> 0
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 1

tf.logical_xor(x, y, name='LogicalXor')


x ^ y = (x | y) & ~(x & y).


출처: Control Flow > Logical Operators


Tensorflow tf.logical_xor 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.logical_xor(tf.cast(const1, tf.bool), tf.cast(const2, tf.bool)))
   ...:     print(str(xs) + " -> " + str(tfutil.get_operation_value(tf.cast(y, tf.int32))))
(0, 0) -> 0
(1, 0) -> 1
(0, 1) -> 1
(1, 1) -> 0


Tensorflow Comparison Operators

TensorFlow provides several operations that you can use to add comparison operators to your graph.


tf.equal(x, y, name=None)


Returns the truth value of (x == y) element-wise.

Args:
  • x: A Tensor. Must be one of the following types: halffloat32float64uint8int8int16int32int64complex64quint8qint8qint32stringboolcomplex128.
  • y: A Tensor. Must have the same type as x.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Comparison Operators


Tensorflow tf.equal 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (1, 0)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.equal(const1, const2))
   ...:     print(str(xs) + " -> " + str(y))
(0, 0) -> True
(1, 0) -> False

tf.not_equal(x, y, name=None)


Returns the truth value of (x != y) element-wise.

Args:
  • x: A Tensor. Must be one of the following types: halffloat32float64uint8int8int16int32int64complex64quint8qint8qint32stringboolcomplex128.
  • y: A Tensor. Must have the same type as x.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Comparison Operators


Tensorflow tf.not_equal 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (1, 0)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.not_equal(const1, const2))
   ...:     print(str(xs) + " -> " + str(y))
(0, 0) -> False
(1, 0) -> False

tf.less(x, y, name=None) 


Returns the truth value of (x < y) element-wise.


Args:

• x : A  Tensor . Must be one of the following types:  float32 ,  float64 ,  int32 ,  int64 ,  uint8 ,  int16 ,  int8 ,  uint16 ,  half .

• y : A  Tensor . Must have the same type as  x .

• name : A name for the operation (optional).


Returns:


A  Tensor  of type  bool .


출처: Control Flow > Comparison Operators


Tensorflow tf.less 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (0, 1), (1, 0)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.less(const1, const2))
   ...:     print(str(xs[0]) + " < " + str(xs[1]) + " -> " + str(y))
0 < 0 -> False
0 < 1 -> True
1 < 0 -> False

tf.less_equal(x, y, name=None)


Returns the truth value of (x <= y) element-wise.

Args:
  • x: A Tensor. Must be one of the following types: float32float64int32int64uint8int16int8uint16half.
  • y: A Tensor. Must have the same type as x.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Comparison Operators


Tensorflow tf.less_equal 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (0, 1), (1, 0)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.less_equal(const1, const2))
   ...:     print(str(xs[0]) + " <= " + str(xs[1]) + " -> " + str(y))
0 <= 0 -> True
0 <= 1 -> True
1 <= 0 -> False


tf.greater(x, y, name=None)


Returns the truth value of (x > y) element-wise.

Args:
  • x: A Tensor. Must be one of the following types: float32float64int32int64uint8int16int8uint16half.
  • y: A Tensor. Must have the same type as x.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Comparison Operators


Tensorflow tf.greater 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (0, 1), (1, 0)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.greater(const1, const2))
   ...:     print(str(xs[0]) + " > " + str(xs[1]) + " -> " + str(y))
0 > 0 -> False
0 > 1 -> False
1 > 0 -> True


tf.greater_equal(x, y, name=None)


Returns the truth value of (x >= y) element-wise.


Args:
  • x: A Tensor. Must be one of the following types: float32float64int32int64uint8int16int8uint16half.
  • y: A Tensor. Must have the same type as x.
  • name: A name for the operation (optional).
Returns:

Tensor of type bool.


출처: Control Flow > Comparison Operators


Tensorflow tf.greater_equal 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: for xs in [(0, 0), (0, 1), (1, 0)]:
   ...:     const1, const2 = tf.constant(xs[0]), tf.constant(xs[1])
   ...:     y = tfutil.get_operation_value(tf.greater_equal(const1, const2))
   ...:     print(str(xs[0]) + " >= " + str(xs[1]) + " -> " + str(y))
0 >= 0 -> True
0 >= 1 -> False
1 >= 0 -> True



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Math

(텐서플로우 수학 함수)


Tensorflow 기본 수학 함수

참조: Tensorflow 수학 함수 API 문서

 

함수

설명

tf.add

덧셈

tf.subtract

뺄셈

tf.multiply

곱셈

tf.div

나눗셈의 몫(Python 2 스타일)

tf.truediv

나눗셈의 몫(Python 3 스타일)

tf.mod

나눗셈의 나머지

tf.abs

절대값을 리턴합니다.

tf.negative

음수를 리턴합니다.

tf.sign

부호를 리턴합니다.(역주음수는 -1, 양수는 1, 0 일땐 0을 리턴합니다)

tf.reciprocal

역수를 리턴합니다.(역주: 3의 역수는 1/3 입니다)

tf.square

제곱을 계산합니다.

tf.round

반올림 값을 리턴합니다.

tf.sqrt

제곱근을 계산합니다.

tf.pow

거듭제곱 값을 계산합니다.

tf.exp

지수 값을 계산합니다.

tf.log

로그 값을 계산합니다.

tf.maximum

최대값을 리턴합니다.

tf.minimum

최소값을 리턴합니다.

tf.cos

코사인 함수 값을 계산합니다.

tf.sin

사인 함수 값을 계산합니다.


Tensorflow Arithmetic Operators 함수 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const1, const2 = tf.constant([1]), tf.constant([2, 3])
In [4]: var1, var2 = tf.Variable([4]), tf.Variable([5, 6])
In [5]: tfutil.print_constant(const1)
[1]
In [6]: tfutil.print_constant(const2)
[2 3]
In [7]: tfutil.print_variable(var1)
[4]
In [8]: tfutil.print_variable(var2)
[5 6]
In [9]: tfutil.print_operation_value(tf.add(const1, var1))
[5]
In [10]: tfutil.print_operation_value(tf.add(const2, var2))
[7 9]
In [11]: tfutil.print_operation_value(tf.subtract(const1, var1))
[-3]
In [12]: tfutil.print_operation_value(tf.subtract(const2, var2))
[-3 -3]
In [13]: tfutil.print_operation_value(tf.multiply(const1, var1))
[4]
In [14]: tfutil.print_operation_value(tf.multiply(const2, var2))
[10 18]
In [15]: tfutil.print_operation_value(tf.div(const1, var1))
[0]
In [16]: tfutil.print_operation_value(tf.div(const2, var2))
[0 0]
In [17]: tfutil.print_operation_value(tf.mod(const1, var1))
[1]
In [18]: tfutil.print_operation_value(tf.mod(const2, var2))
[2 3]
In [19]: tfutil.print_operation_value(tf.square(var1))
[16]
In [20]: tfutil.print_operation_value(tf.square(var2))
[25 36]
In [21]: tfutil.print_operation_value(tf.square(const1))
[1]
In [22]: tfutil.print_operation_value(tf.square(const2))
[4 9]


이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Convert to Tensor - slicing and joining

(텐서플로우 텐서 변환 - 자르고 붙이기)


자르고 붙이기

TensorFlow는 텐서를 자르고 특정 부분을 추출해내거나, 여러 텐서를 붙일 수 있는 몇 가지 함수를 제공합니다.


tf.slice(input_, begin, size, name=None)


텐서의 특정 부분을 추출합니다.


이 함수는 텐서 input에서 begin 위치에서 시작해 크기 size인 부분을 추출합니다. 추출할 부분의 size는 텐서 구조(shape)로 표현되는데, size[i]가 input에서 추출할 i번째 차원의 원소의 수입니다. 추출 부분의 시작 위치 begin은 각 차원에서의 오프셋(offset)으로 표현됩니다. 즉, begin[i]는 input의 i번째 차원에서 시작 위치의 오프셋입니다.


begin은 0부터 시작하고, size는 1부터 시작합니다. 만약 size[i]가 -1이라면, 차원 i의 모든 남은 원소들이 추출 부분에 포함됩니다. 즉, 이는 아래와 같이 설정하는 것과 동일합니다.

size[i] = input.dim_size(i) - begin[i]


이 함수는 다음의 조건이 만족되어야 합니다:

0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]


예시:

# 'input'은 [[[1, 1, 1], [2, 2, 2]],

#            [[3, 3, 3], [4, 4, 4]],

#            [[5, 5, 5], [6, 6, 6]]]

tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]]

tf.slice(input, [1, 0, 0], [1, 2, 3]) ==> [[[3, 3, 3],

                                            [4, 4, 4]]]

tf.slice(input, [1, 0, 0], [2, 1, 3]) ==> [[[3, 3, 3]],

                                           [[5, 5, 5]]]

인자:
  • input_Tensor.
  • beginint32 또는 int64형 Tensor.
  • sizeint32 또는 int64형 Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.slice 결과

In [1]:

import tensorflow as tf

import tfutil

 

# [1, 2, 3, 4, 5, 6, 7, 8, 9]

const1 = tf.constant([123456789])

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(9,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 2 3 4 5 6 7 8 9]

In [2]:

sl_const1 = tf.slice(const1, [2], [3])

print(sl_const1)

print(tf.shape(sl_const1))

tfutil.print_operation_value(sl_const1)

Tensor("Slice:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[3 4 5]

In [3]:

# [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19,20]]

const2 = tf.constant([[12345678910], [111213141516171819,20]])

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 10), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[ 1  2  3  4  5  6  7  8  9 10]

 [11 12 13 14 15 16 17 18 19 20]]

In [4]:

sl_const2 = tf.slice(const2, [01], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_1:0", shape=(1, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[2 3 4]]

In [5]:

sl_const2 = tf.slice(const2, [02], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_2:0", shape=(1, 3), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[3 4 5]]

In [6]:

sl_const2 = tf.slice(const2, [11], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_3:0", shape=(1, 3), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[12 13 14]]

In [7]:

sl_const2 = tf.slice(const2, [12], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_4:0", shape=(1, 3), dtype=int32)

Tensor("Shape_6:0", shape=(2,), dtype=int32)

[[13 14 15]]

In [8]:

# [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]

const3 = tf.constant([[[123], [456]], [[789], [101112]], [[131415], [161718]]])

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(3, 2, 3), dtype=int32)

Tensor("Shape_7:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]

 [[13 14 15]

  [16 17 18]]]

In [9]:

sl_const3 = tf.slice(const3, [000], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_5:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_8:0", shape=(3,), dtype=int32)

[[[1]]]

In [10]:

sl_const3 = tf.slice(const3, [000], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_6:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_9:0", shape=(3,), dtype=int32)

[[[1 2]]]

In [11]:

sl_const3 = tf.slice(const3, [010], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_7:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_10:0", shape=(3,), dtype=int32)

[[[4]]]

In [12]:

sl_const3 = tf.slice(const3, [010], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_8:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_11:0", shape=(3,), dtype=int32)

[[[4 5]]]

In [13]:

sl_const3 = tf.slice(const3, [100], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_9:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_12:0", shape=(3,), dtype=int32)

[[[7]]]

In [14]:

sl_const3 = tf.slice(const3, [100], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_10:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_13:0", shape=(3,), dtype=int32)

[[[7 8]]]

In [15]:

sl_const3 = tf.slice(const3, [110], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_11:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_14:0", shape=(3,), dtype=int32)

[[[10]]]

In [16]:

sl_const3 = tf.slice(const3, [110], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_12:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_15:0", shape=(3,), dtype=int32)

[[[10 11]]]

In [17]:

sl_const3 = tf.slice(const3, [200], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_13:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_16:0", shape=(3,), dtype=int32)

[[[13]]]

In [18]:

sl_const3 = tf.slice(const3, [200], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_14:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_17:0", shape=(3,), dtype=int32)

[[[13 14]]]

In [19]:

sl_const3 = tf.slice(const3, [210], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_15:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_18:0", shape=(3,), dtype=int32)

[[[16]]]

In [20]:

sl_const3 = tf.slice(const3, [210], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_16:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_19:0", shape=(3,), dtype=int32)

[[[16 17]]]

In [21]:

# [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]

sl_const3 = tf.slice(const3, [000], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_17:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_20:0", shape=(3,), dtype=int32)

[[[1]]]

In [22]:

sl_const3 = tf.slice(const3, [000], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_18:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_21:0", shape=(3,), dtype=int32)

[[[1 2]]]

In [23]:

sl_const3 = tf.slice(const3, [000], [113])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_19:0", shape=(1, 1, 3), dtype=int32)

Tensor("Shape_22:0", shape=(3,), dtype=int32)

[[[1 2 3]]]

In [24]:

sl_const3 = tf.slice(const3, [000], [121])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_20:0", shape=(1, 2, 1), dtype=int32)

Tensor("Shape_23:0", shape=(3,), dtype=int32)

[[[1]

  [4]]]

In [25]:

sl_const3 = tf.slice(const3, [000], [122])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_21:0", shape=(1, 2, 2), dtype=int32)

Tensor("Shape_24:0", shape=(3,), dtype=int32)

[[[1 2]

  [4 5]]]

In [26]:

sl_const3 = tf.slice(const3, [000], [123])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_22:0", shape=(1, 2, 3), dtype=int32)

Tensor("Shape_25:0", shape=(3,), dtype=int32)

[[[1 2 3]

  [4 5 6]]]

In [27]:

sl_const3 = tf.slice(const3, [000], [311])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_23:0", shape=(3, 1, 1), dtype=int32)

Tensor("Shape_26:0", shape=(3,), dtype=int32)

[[[ 1]]

 [[ 7]]

 [[13]]]

In [28]:

sl_const3 = tf.slice(const3, [000], [321])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_24:0", shape=(3, 2, 1), dtype=int32)

Tensor("Shape_27:0", shape=(3,), dtype=int32)

[[[ 1]

  [ 4]]

 [[ 7]

  [10]]

 [[13]

  [16]]]

In [29]:

sl_const3 = tf.slice(const3, [000], [312])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_25:0", shape=(3, 1, 2), dtype=int32)

Tensor("Shape_28:0", shape=(3,), dtype=int32)

[[[ 1  2]]

 [[ 7  8]]

 [[13 14]]]

In [30]:

sl_const3 = tf.slice(const3, [000], [322])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_26:0", shape=(3, 2, 2), dtype=int32)

Tensor("Shape_29:0", shape=(3,), dtype=int32)

[[[ 1  2]

  [ 4  5]]

 [[ 7  8]

  [10 11]]

 [[13 14]

  [16 17]]]

In [31]:

sl_const3 = tf.slice(const3, [000], [313])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_27:0", shape=(3, 1, 3), dtype=int32)

Tensor("Shape_30:0", shape=(3,), dtype=int32)

[[[ 1  2  3]]

 [[ 7  8  9]]

 [[13 14 15]]]

In [32]:

sl_const3 = tf.slice(const3, [000], [323])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_28:0", shape=(3, 2, 3), dtype=int32)

Tensor("Shape_31:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]

 [[13 14 15]

  [16 17 18]]]


tf.split(split_dim, num_split, value, name='split')


한 차원을 따라서 입력된 텐서를 num_split개의 텐서로 분리합니다.


split_dim 차원을 따라서 value를 num_split 개의 작은 텐서로 분리합니다. num_split이 value.shape[split_dim]을 나눌 수 있어야 합니다.


예시:

# 'value'는 구조(shape) [5, 30]의 텐서

# 'value'를 차원 1을 따라 3개의 텐서로 분리

split0, split1, split2 = tf.split(1, 3, value)

tf.shape(split0) ==> [5, 10]

인자:
  • split_dim: 0-D int32 Tensor. 텐서를 분리할 차원. [0, rank(value)) 범위 내에 있어야 합니다.
  • num_split: Python 정수. 텐서를 분리할 개수.
  • value: 분리할 Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

value를 분리하여 얻어진 num_split개의 Tensor.


출처: 텐서 변환


Tensorflow tf.split 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

 

# [1, 2, 3, 4, 5, 6, 7, 8, 9]

const1 = tf.constant(np.array([12345678910]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(10,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10]

In [2]:

sp1_const1, sp2_const1 = tf.split(const1, 20)

print(sp1_const1)

print(tf.shape(sp1_const1))

tfutil.print_operation_value(sp1_const1)

Tensor("split:0", shape=(5,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2 3 4 5]

In [3]:

print(sp2_const1)

print(tf.shape(sp2_const1))

tfutil.print_operation_value(sp2_const1)

Tensor("split:1", shape=(5,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[ 6  7  8  9 10]

In [4]:

# [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]

const2 = tf.constant([[1234], [5678], [9101112], [13141516], [17181920]])

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_2:0", shape=(5, 4), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[ 1  2  3  4]

 [ 5  6  7  8]

 [ 9 10 11 12]

 [13 14 15 16]

 [17 18 19 20]]

In [5]:

sp1_const2, sp2_const2 = tf.split(const2, 21)

print(sp1_const2)

print(tf.shape(sp1_const2))

tfutil.print_operation_value(sp1_const2)

Tensor("split_1:0", shape=(5, 2), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[ 1  2]

 [ 5  6]

 [ 9 10]

 [13 14]

 [17 18]]

In [6]:

print(sp2_const2)

print(tf.shape(sp2_const2))

tfutil.print_operation_value(sp2_const2)

Tensor("split_1:1", shape=(5, 2), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[ 3  4]

 [ 7  8]

 [11 12]

 [15 16]

 [19 20]]

In [7]:

# [5, 30]

var1 = tf.Variable(tf.random_normal([530]))

print(var1)

print(tf.shape(var1))

<tf.Variable 'Variable:0' shape=(5, 30) dtype=float32_ref>

Tensor("Shape_6:0", shape=(2,), dtype=int32)

In [8]:

sp1_var1, sp2_var1, sp3_var1 = tf.split(var1, 31)

print(sp1_var1)

print(tf.shape(sp1_var1))

Tensor("split_2:0", shape=(5, 10), dtype=float32)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

In [9]:

print(sp2_var1)

print(tf.shape(sp2_var1))

Tensor("split_2:1", shape=(5, 10), dtype=float32)

Tensor("Shape_8:0", shape=(2,), dtype=int32)

In [10]:

print(sp3_var1)

print(tf.shape(sp3_var1))

Tensor("split_2:2", shape=(5, 10), dtype=float32)

Tensor("Shape_9:0", shape=(2,), dtype=int32)


tf.tile(input, multiples, name=None)


주어진 텐서를 타일링(tiling)하여 새로운 텐서를 만듭니다.


이 함수는 주어진 텐서 input을 multiples회 복사하여 새로운 텐서를 만듭니다. 출력 텐서의 i번째 차원은 input.dims(i) * multiples[i] 개의 원소를 가지고, 이는 input의 원소들이 multiples[i]번 복사된 것에 해당합니다. 예로, [a b c d]를 [2]로 타일링하면 [a b c d a b c d]를 얻습니다.

인자:
  • input: 1-D 혹은 그 이상의 Tensor.
  • multiplesint32형 Tensor. 1-D. 길이는 input의 차원의 수와 같아야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.tile 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [1, 2, 3, 4, 5, 6, 7, 8, 9]

const1 = tf.constant(np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(10,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10]

In [3]:

ti_const1 = tf.tile(const1, [1])

print(ti_const1)

print(tf.shape(ti_const1))

tfutil.print_operation_value(ti_const1)

Tensor("Tile:0", shape=(10,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10]

In [4]:

ti_const1 = tf.tile(const1, [2])

print(ti_const1)

print(tf.shape(ti_const1))

tfutil.print_operation_value(ti_const1)

Tensor("Tile_1:0", shape=(20,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10]

In [5]:

ti_const1 = tf.tile(const1, [3])

print(ti_const1)

print(tf.shape(ti_const1))

tfutil.print_operation_value(ti_const1)

Tensor("Tile_2:0", shape=(30,), dtype=int32)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5

  6  7  8  9 10]


tf.pad(tensor, paddings, mode='CONSTANT', name=None)


텐서에 패딩을 적용합니다.


이 함수는 지정한 paddings에 따라 tensor에 패딩을 적용합니다. padding은 구조(shape)가 [n, 2]인 정수형 텐서이고, 여기서 n은 tensor의 랭크(rank)입니다. input의 각각의 차원 D에 대해, paddings[D, 0]은 tensor의 원소 앞에 몇 개의 값을 넣을 것인지, paddings[D, 1]은 tensor의 원소 뒤에 몇 개의 값을 넣을 것인지를 나타냅니다. 만약 mode가 "REFLECT"라면, paddings[D, 0]과 paddings[D, 1] 모두 tensor.dim_size(D) - 1보다 크지 않아야 합니다. mode가 "SYMMETRIC"이라면, paddings[D, 0]과 paddings[D, 1] 모두 tensor.dim_size(D)보다 크지 않아야 합니다.


패딩이 이루어진 뒤 출력에서 차원 D의 길이는 다음과 같습니다.

paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]


예시:

# 't'는 [[1, 2, 3], [4, 5, 6]].

# 'paddings'는 [[1, 1,], [2, 2]].

# 't'의 랭크(rank)는 2.

pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0],

                                  [0, 0, 1, 2, 3, 0, 0],

                                  [0, 0, 4, 5, 6, 0, 0],

                                  [0, 0, 0, 0, 0, 0, 0]]


pad(t, paddings, "REFLECT") ==> [[6, 5, 4, 5, 6, 5, 4],

                                 [3, 2, 1, 2, 3, 2, 1],

                                 [6, 5, 4, 5, 6, 5, 4],

                                 [3, 2, 1, 2, 3, 2, 1]]


pad(t, paddings, "SYMMETRIC") ==> [[2, 1, 1, 2, 3, 3, 2],

                                   [2, 1, 1, 2, 3, 3, 2],

                                   [5, 4, 4, 5, 6, 6, 5],

                                   [5, 4, 4, 5, 6, 6, 5]]

인자:
  • tensorTensor.
  • paddingsint32형 Tensor.
  • mode: "CONSTANT", "REFLECT", "SYMMETRIC" 중 하나.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

tensor와 같은 자료형의 Tensor.

예외:
  • ValueError: 모드가 "CONSTANT", "REFLECT", or "SYMMETRIC" 중의 하나가 아닌 경우.

출처: 텐서 변환


Tensorflow tf.pad 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [[1, 2, 3], [4, 5, 6]]

const1 = tf.constant(np.array([[1, 2, 3], [4, 5, 6]]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 3), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [3]:

paddings =  [[0, 0,], [0, 1]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad:0", shape=(2, 4), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[1 2 3 0]

 [4 5 6 0]]

In [4]:

paddings =  [[0, 0,], [1, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_1:0", shape=(2, 4), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[0 1 2 3]

 [0 4 5 6]]

In [5]:

paddings =  [[0, 0,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_2:0", shape=(2, 5), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[0 1 2 3 0]

 [0 4 5 6 0]]

In [6]:

paddings =  [[0, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_3:0", shape=(3, 3), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [0 0 0]]

In [7]:

paddings =  [[1, 0,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_4:0", shape=(3, 3), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[0 0 0]

 [1 2 3]

 [4 5 6]]

In [8]:

paddings =  [[1, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_5:0", shape=(4, 3), dtype=int32)

Tensor("Shape_6:0", shape=(2,), dtype=int32)

[[0 0 0]

 [1 2 3]

 [4 5 6]

 [0 0 0]]

In [9]:

paddings =  [[1, 1,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_6:0", shape=(4, 5), dtype=int32)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[[0 0 0 0 0]

 [0 1 2 3 0]

 [0 4 5 6 0]

 [0 0 0 0 0]]

In [10]:

# [[1, 2, 3], [4, 5, 6]]

paddings =  [[0, 0,], [0, 1]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad:0", shape=(2, 4), dtype=int32)

Tensor("Shape_8:0", shape=(2,), dtype=int32)

[[1 2 3 2]

 [4 5 6 5]]

In [11]:

paddings =  [[0, 0,], [1, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_1:0", shape=(2, 4), dtype=int32)

Tensor("Shape_9:0", shape=(2,), dtype=int32)

[[2 1 2 3]

 [5 4 5 6]]

In [12]:

paddings =  [[0, 0,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_2:0", shape=(2, 5), dtype=int32)

Tensor("Shape_10:0", shape=(2,), dtype=int32)

[[2 1 2 3 2]

 [5 4 5 6 5]]

In [13]:

paddings =  [[0, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_3:0", shape=(3, 3), dtype=int32)

Tensor("Shape_11:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [1 2 3]]

In [14]:

paddings =  [[1, 0,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_4:0", shape=(3, 3), dtype=int32)

Tensor("Shape_12:0", shape=(2,), dtype=int32)

[[4 5 6]

 [1 2 3]

 [4 5 6]]

In [15]:

paddings =  [[1, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_5:0", shape=(4, 3), dtype=int32)

Tensor("Shape_13:0", shape=(2,), dtype=int32)

[[4 5 6]

 [1 2 3]

 [4 5 6]

 [1 2 3]]

In [16]:

paddings =  [[1, 1,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_6:0", shape=(4, 5), dtype=int32)

Tensor("Shape_14:0", shape=(2,), dtype=int32)

[[5 4 5 6 5]

 [2 1 2 3 2]

 [5 4 5 6 5]

 [2 1 2 3 2]]

In [17]:

paddings =  [[1, 1,], [2, 2]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_7:0", shape=(4, 7), dtype=int32)

Tensor("Shape_15:0", shape=(2,), dtype=int32)

[[6 5 4 5 6 5 4]

 [3 2 1 2 3 2 1]

 [6 5 4 5 6 5 4]

 [3 2 1 2 3 2 1]]

In [18]:

# [[1, 2, 3], [4, 5, 6]]

paddings =  [[0, 0,], [0, 1]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_8:0", shape=(2, 4), dtype=int32)

Tensor("Shape_16:0", shape=(2,), dtype=int32)

[[1 2 3 3]

 [4 5 6 6]]

In [19]:

paddings =  [[0, 0,], [1, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_9:0", shape=(2, 4), dtype=int32)

Tensor("Shape_17:0", shape=(2,), dtype=int32)

[[1 1 2 3]

 [4 4 5 6]]

In [20]:

paddings =  [[0, 0,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_10:0", shape=(2, 5), dtype=int32)

Tensor("Shape_18:0", shape=(2,), dtype=int32)

[[1 1 2 3 3]

 [4 4 5 6 6]]

In [21]:

paddings =  [[0, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_11:0", shape=(3, 3), dtype=int32)

Tensor("Shape_19:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [4 5 6]]

In [22]:

paddings =  [[1, 0,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_12:0", shape=(3, 3), dtype=int32)

Tensor("Shape_20:0", shape=(2,), dtype=int32)

[[1 2 3]

 [1 2 3]

 [4 5 6]]

In [23]:

paddings =  [[1, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_13:0", shape=(4, 3), dtype=int32)

Tensor("Shape_21:0", shape=(2,), dtype=int32)

[[1 2 3]

 [1 2 3]

 [4 5 6]

 [4 5 6]]

In [24]:

paddings =  [[1, 1,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_14:0", shape=(4, 5), dtype=int32)

Tensor("Shape_22:0", shape=(2,), dtype=int32)

[[1 1 2 3 3]

 [1 1 2 3 3]

 [4 4 5 6 6]

 [4 4 5 6 6]]

In [25]:

paddings =  [[1, 1,], [2, 2]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_15:0", shape=(4, 7), dtype=int32)

Tensor("Shape_23:0", shape=(2,), dtype=int32)

[[2 1 1 2 3 3 2]

 [2 1 1 2 3 3 2]

 [5 4 4 5 6 6 5]

 [5 4 4 5 6 6 5]]

In [26]:

paddings =  [[1, 1,], [3, 3]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_16:0", shape=(4, 9), dtype=int32)

Tensor("Shape_24:0", shape=(2,), dtype=int32)

[[3 2 1 1 2 3 3 2 1]

 [3 2 1 1 2 3 3 2 1]

 [6 5 4 4 5 6 6 5 4]

 [6 5 4 4 5 6 6 5 4]]


tf.concat(concat_dim, values, name='concat')


텐서들을 하나의 차원에서 이어붙입니다.


텐서들의 리스트 values를 차원 concat_dim에서 이어붙입니다. 만약 values[i].shape = [D0, D1, ... Dconcat_dim(i), ...Dn]이면, 이어붙인 결과의 구조(shape)는 아래와 같습니다.


[D0, D1, ... Rconcat_dim, ...Dn]


여기서,

Rconcat_dim = sum(Dconcat_dim(i))


입니다. 즉, concat_dim 차원을 따라 입력된 텐서들의 데이터가 연결됩니다.


입력할 텐서들의 차원의 수는 모두 동일해야 하며, concat_dim 차원을 제외한 모든 차원의 길이가 동일해야 합니다.


예시:

t1 = [[1, 2, 3], [4, 5, 6]]

t2 = [[7, 8, 9], [10, 11, 12]]

tf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]


# tensor t3의 구조(shape)는 [2, 3]

# tensor t4의 구조(shape)는 [2, 3]

tf.shape(tf.concat(0, [t3, t4])) ==> [4, 3]

tf.shape(tf.concat(1, [t3, t4])) ==> [2, 6]

인자:
  • concat_dim: 0-D int32형 Tensor. 텐서를 이어붙일 차원.
  • valuesTensor들의 리스트 또는 Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

입력 텐서들을 이어붙여 만든 Tensor.


출처: 텐서 변환


Tensorflow tf. 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [[1, 2, 3], [4, 5, 6]]

const1 = tf.constant(np.array([[1, 2, 3], [4, 5, 6]]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 3), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [3]:

# [[7, 8, 9], [10, 11, 12]]

const2 = tf.constant(np.array([[7, 8, 9], [10, 11, 12]]), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 3), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[ 7  8  9]

 [10 11 12]]

In [4]:

cc_const1 = tf.concat([const1, const2], 0)

print(cc_const1)

print(tf.shape(cc_const1))

tfutil.print_operation_value(cc_const1)

Tensor("concat:0", shape=(4, 3), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[ 1  2  3]

 [ 4  5  6]

 [ 7  8  9]

 [10 11 12]]

In [5]:

cc_const1 = tf.concat([const1, const2], 1)

print(cc_const1)

print(tf.shape(cc_const1))

tfutil.print_operation_value(cc_const1)

Tensor("concat_1:0", shape=(2, 6), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[ 1  2  3  7  8  9]

 [ 4  5  6 10 11 12]]


tf.stack(values, axis=0, name='stack')


Defined in tensorflow/python/ops/array_ops.py.

See the guides: Layers (contrib) > Higher level ops for building neural network layersTensor Transformations > Slicing and Joining

Stacks a list of rank-R tensors into one rank-(R+1) tensor.

Packs the list of tensors in values into a tensor with rank one higher than each tensor in values, by packing them along the axis dimension. Given a list of length N of tensors of shape (A, B, C);

if axis == 0 then the output tensor will have the shape (N, A, B, C). if axis == 1 then the output tensor will have the shape (A, N, B, C). Etc.

For example:

x = tf.constant([1, 4])
y
= tf.constant([2, 5])
z
= tf.constant([3, 6])
tf
.stack([x, y, z])  # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.)
tf
.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]

This is the opposite of unstack. The numpy equivalent is

tf.stack([x, y, z]) = np.stack([x, y, z])

Args:

  • values: A list of Tensor objects with the same shape and type.
  • axis: An int. The axis to stack along. Defaults to the first dimension. Negative values wrap around, so the valid range is [-(R+1), R+1).
  • name: A name for this operation (optional).

Returns:

  • output: A stacked Tensor with the same type as values.

Raises:

  • ValueError: If axis is out of the range [-(R+1), R+1).

출처: API r1.4


Tensorflow tf.stack 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [[1, 2, 3], [4, 5, 6]]

# [[7, 8, 9], [10, 11, 12]]

const1 = tf.constant(np.array([1, 2, 3]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 2 3]

In [3]:

const2 = tf.constant(np.array([4, 5, 6]), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[4 5 6]

In [4]:

const3 = tf.constant(np.array([7, 8, 9]), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(3,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[7 8 9]

In [5]:

pack_const1 = tf.stack([const1, const2, const3])

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack:0", shape=(3, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [6]:

pack_const1 = tf.stack([const1, const2, const3], axis=1)

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack_1:0", shape=(3, 3), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[1 4 7]

 [2 5 8]

 [3 6 9]]


tf.unstack(value, num=None, axis=0, name='unstack')


Defined in tensorflow/python/ops/array_ops.py.
See the guide: Tensor Transformations > Slicing and Joining

Unpacks the given dimension of a rank-R tensor into rank-(R-1) tensors.Unpacks num tensors from value by chipping it along the axis dimension. If num is not specified (the default), it is inferred from value's shape. If value.shape[axis] is not known, ValueError is raised.

For example, given a tensor of shape (A, B, C, D);

If axis == 0 then the i'th tensor in output is the slice value[i, :, :, :] and each tensor in output will have shape (B, C, D). (Note that the dimension unpacked along is gone, unlike split).

If axis == 1 then the i'th tensor in output is the slice value[:, i, :, :] and each tensor in output will have shape (A, C, D). Etc.

This is the opposite of stack. The numpy equivalent is

tf.unstack(x, n) = np.unstack(x)

Args:

  • value: A rank R > 0 Tensor to be unstacked.
  • num: An int. The length of the dimension axis. Automatically inferred if None (the default).
  • axis: An int. The axis to unstack along. Defaults to the first dimension. Negative values wrap around, so the valid range is [-R, R).
  • name: A name for the operation (optional).

Returns:
The list of Tensor objects unstacked from value.


Raises:

  • ValueError: If num is unspecified and cannot be inferred.
  • ValueError: If axis is out of the range [-R, R).

출처: 텐서 변환


Tensorflow tf.unstack 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

const1 = tf.constant(np.array([1, 2, 3]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 2 3]

In [3]:

const2 = tf.constant(np.array([4, 5, 6]), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[4 5 6]

In [4]:

const3 = tf.constant(np.array([7, 8, 9]), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(3,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[7 8 9]

In [5]:

pack_const1 = tf.stack([const1, const2, const3])

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack:0", shape=(3, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [6]:

up_const1, up_const2, up_const3 = tf.unstack(pack_const1)

print(up_const1)

print(tf.shape(up_const1))

tfutil.print_constant(up_const1)

Tensor("unstack:0", shape=(3,), dtype=int32)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[1 2 3]

In [7]:

print(up_const2)

print(tf.shape(up_const2))

tfutil.print_constant(up_const2)

Tensor("unstack:1", shape=(3,), dtype=int32)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[4 5 6]

In [8]:

print(up_const3)

print(tf.shape(up_const3))

tfutil.print_constant(up_const3)

Tensor("unstack:2", shape=(3,), dtype=int32)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[7 8 9]

In [9]:

pack_const1 = tf.stack([const1, const2, const3], axis=1)

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack_1:0", shape=(3, 3), dtype=int32)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[[1 4 7]

 [2 5 8]

 [3 6 9]]

In [10]:

up_const1, up_const2, up_const3 = tf.unstack(pack_const1)

print(up_const1)

print(tf.shape(up_const1))

tfutil.print_constant(up_const1)

Tensor("unstack_1:0", shape=(3,), dtype=int32)

Tensor("Shape_8:0", shape=(1,), dtype=int32)

[1 4 7]

In [11]:

print(up_const2)

print(tf.shape(up_const2))

tfutil.print_constant(up_const2)

Tensor("unstack_1:1", shape=(3,), dtype=int32)

Tensor("Shape_9:0", shape=(1,), dtype=int32)

[2 5 8]

In [12]:

print(up_const3)

print(tf.shape(up_const3))

tfutil.print_constant(up_const3)

Tensor("unstack_1:2", shape=(3,), dtype=int32)

Tensor("Shape_10:0", shape=(1,), dtype=int32)

[3 6 9]


tf.reverse_sequence(input, seq_lengths, seq_dim, batch_dim=None, name=None)


텐서를 특정한 부분을 반전시킵니다.


이 함수는 먼저 input을 batch_dim 차원을 따라 여러 개의 슬라이스로 나눕니다. 그리고 각각의 슬라이스 i에서 seq_dim 차원을 따라 처음 seq_lengths[i]개의 원소들이 반전됩니다.


seq_lengths의 원소들은 seq_lengths[i] < input.dims[seq_dim]을 만족해야 하고, seq_lengths는 길이 input.dims[batch_dim]의 벡터여야 합니다.


반환될 텐서에서 batch_dim 차원의 i번째 슬라이스는, 입력 텐서의 i번째 슬라이스에서 seq_dim 차원을 따라 첫 seq_lengths[i] 개의 원소들이 반전된 것과 같습니다.


예시:

# 다음과 같이 설정합니다.

batch_dim = 0

seq_dim = 1

input.dims = (4, 8, ...)

seq_lengths = [7, 2, 3, 5]


# 입력 텐서의 각각의 슬라이스는 seq_dim 차원에서 seq_lengths 까지 반전됩니다.

output[0, 0:7, :, ...] = input[0, 7:0:-1, :, ...]

output[1, 0:2, :, ...] = input[1, 2:0:-1, :, ...]

output[2, 0:3, :, ...] = input[2, 3:0:-1, :, ...]

output[3, 0:5, :, ...] = input[3, 5:0:-1, :, ...]


# seq_lengths 이후의 부분은 그대로 들어갑니다.

output[0, 7:, :, ...] = input[0, 7:, :, ...]

output[1, 2:, :, ...] = input[1, 2:, :, ...]

output[2, 3:, :, ...] = input[2, 3:, :, ...]

output[3, 2:, :, ...] = input[3, 2:, :, ...]


다른 예시:

# 다음과 같이 설정합니다.
batch_dim = 2
seq_dim = 0
input.dims = (8, ?, 4, ...)
seq_lengths = [7, 2, 3, 5]

# 입력 텐서의 각각의 슬라이스는 seq_dim 차원에서 seq_lengths 까지 반전됩니다.
output[0:7, :, 0, :, ...] = input[7:0:-1, :, 0, :, ...]
output[0:2, :, 1, :, ...] = input[2:0:-1, :, 1, :, ...]
output[0:3, :, 2, :, ...] = input[3:0:-1, :, 2, :, ...]
output[0:5, :, 3, :, ...] = input[5:0:-1, :, 3, :, ...]

# seq_lengths 이후의 부분은 그대로 들어갑니다.
output[7:, :, 0, :, ...] = input[7:, :, 0, :, ...]
output[2:, :, 1, :, ...] = input[2:, :, 1, :, ...]
output[3:, :, 2, :, ...] = input[3:, :, 2, :, ...]
output[2:, :, 3, :, ...] = input[2:, :, 3, :, ...]
인자:
  • inputTensor. 반전시킬 텐서.
  • seq_lengthsint64형 1-D Tensor. 길이는 input.dims(batch_dim) 이며, max(seq_lengths) < input.dims(seq_dim)을 만족합니다.
  • seq_dimint. (부분적으로) 반전되는 차원.
  • batch_dimint. 텐서의 반전이 이루어지는 차원, 기본값은 0. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형과 구조(shape)의 Tensorinput의 일부분이 반전되어 있습니다.


출처: 텐서 변환


Tensorflow tf.reverse_sequence 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[1, 2, 3, 4, 0, 0, 0],

     [1, 2, 3, 0, 0, 0, 0],

     [1, 2, 3, 4, 5, 6, 7]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3, 7), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3 4 0 0 0]

 [1 2 3 0 0 0 0]

 [1 2 3 4 5 6 7]]

In [3]:

seq_lens = [4, 3, 7]

rs_const1 = tf.reverse_sequence(const1, seq_lens, seq_dim=1, batch_dim=0)

print(rs_const1)

print(tf.shape(rs_const1))

tfutil.print_operation_value(rs_const1)

Tensor("ReverseSequence:0", shape=(3, 7), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[4 3 2 1 0 0 0]

 [3 2 1 0 0 0 0]

 [7 6 5 4 3 2 1]]

In [4]:

x = [[[1, 2, 3, 4, 0, 0, 0], [1, 0, 2, 0, 0, 0, 0]],

     [[1, 2, 3, 4, 5, 0, 0], [0, 2, 1, 4, 0, 0, 0]],

     [[1, 2, 3, 4, 5, 6 ,7], [1, 2, 3, 4, 0, 6, 0]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3, 2, 7), dtype=int32)

Tensor("Shape_2:0", shape=(3,), dtype=int32)

[[[1 2 3 4 0 0 0]

  [1 0 2 0 0 0 0]]

 [[1 2 3 4 5 0 0]

  [0 2 1 4 0 0 0]]

 [[1 2 3 4 5 6 7]

  [1 2 3 4 0 6 0]]]

In [5]:

seq_lens = [4, 3, 5]

rs_const2 = tf.reverse_sequence(const2, seq_lens, seq_dim=2, batch_dim=0)

print(rs_const2)

print(tf.shape(rs_const2))

tfutil.print_operation_value(rs_const2)

Tensor("ReverseSequence_1:0", shape=(3, 2, 7), dtype=int32)

Tensor("Shape_3:0", shape=(3,), dtype=int32)

[[[4 3 2 1 0 0 0]

  [0 2 0 1 0 0 0]]

 [[3 2 1 4 5 0 0]

  [1 2 0 4 0 0 0]]

 [[5 4 3 2 1 6 7]

  [0 4 3 2 1 6 0]]]

In [6]:

seq_lens = [4, 3]

rs_const2 = tf.reverse_sequence(const2, seq_lens, seq_dim=2, batch_dim=1)

print(rs_const2)

print(tf.shape(rs_const2))

tfutil.print_operation_value(rs_const2)

Tensor("ReverseSequence_2:0", shape=(3, 2, 7), dtype=int32)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[[4 3 2 1 0 0 0]

  [2 0 1 0 0 0 0]]

 [[4 3 2 1 5 0 0]

  [1 2 0 4 0 0 0]]

 [[4 3 2 1 5 6 7]

  [3 2 1 4 0 6 0]]]


tf.reverse(tensor, dims, name=None)


텐서의 특정 차원을 반전시킵니다.


tensor와 그 텐서의 각 차원에 해당하는 bool형 텐서 dims가 주어졌을 때, 이 함수는 dims[i]가 True인 경우 tensor의 차원 i를 반전시킵니다.


tensor는 차원을 8개까지 가질 수 있습니다. tensor의 차원의 수는 dims의 원소의 수와 동일해야 합니다. 즉, 다음의 식이 성립해야 합니다.

rank(tensor) = size(dims)

예시:

# tensor 't'는 [[[[ 0,  1,  2,  3],

#                 [ 4,  5,  6,  7],

#                 [ 8,  9, 10, 11]],

#                [[12, 13, 14, 15],

#                 [16, 17, 18, 19],

#                 [20, 21, 22, 23]]]]

# tensor 't'의 구조(shape)는 [1, 2, 3, 4]


# 'dims'가 [3] 일 때

reverse(t, dims) ==> [[[[ 3,  2,  1,  0],

                        [ 7,  6,  5,  4],

                        [ 11, 10, 9, 8]],

                       [[15, 14, 13, 12],

                        [19, 18, 17, 16],

                        [23, 22, 21, 20]]]]


# 'dims'가 [1] 일 때

reverse(t, dims) ==> [[[[12, 13, 14, 15],

                        [16, 17, 18, 19],

                        [20, 21, 22, 23]

                       [[ 0,  1,  2,  3],

                        [ 4,  5,  6,  7],

                        [ 8,  9, 10, 11]]]]


# 'dims'가 [2] 일 때

reverse(t, dims) ==> [[[[8, 9, 10, 11],

                        [4, 5, 6, 7],

                        [0, 1, 2, 3]]

                       [[20, 21, 22, 23],

                        [16, 17, 18, 19],

                        [12, 13, 14, 15]]]]

인자:
  • tensorTensor. 자료형이 uint8int8int32boolhalffloat32float64 중 하나여야 합니다. Up to 8-D.
  • dimsbool형 1-D Tensor. 반전시킬 차원을 나타냅니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

tensor와 자료형과 구조(shape)가 같은 Tensor.


출처: 텐서 변환


Tensorflow tf.reverse 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[ 0123],

        [ 4567],

        [ 89, 10, 11]],

        [[12, 13, 14, 15],

        [16, 17, 18, 19],

        [20, 21, 22, 23]]]]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[ 0  1  2  3]

   [ 4  5  6  7]

   [ 8  9 10 11]]

  [[12 13 14 15]

   [16 17 18 19]

   [20 21 22 23]]]]

In [3]:

dims = [3]

dims_const1 = tf.reverse(const1, dims)

print(dims_const1)

print(tf.shape(dims_const1))

tfutil.print_operation_value(dims_const1)

Tensor("ReverseV2:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[ 3  2  1  0]

   [ 7  6  5  4]

   [11 10  9  8]]

  [[15 14 13 12]

   [19 18 17 16]

   [23 22 21 20]]]]

In [4]:

dims = [1]

dims_const1 = tf.reverse(const1, dims)

print(dims_const1)

print(tf.shape(dims_const1))

tfutil.print_operation_value(dims_const1)

Tensor("ReverseV2_1:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[12 13 14 15]

   [16 17 18 19]

   [20 21 22 23]]

  [[ 0  1  2  3]

   [ 4  5  6  7]

   [ 8  9 10 11]]]]

In [5]:

 dims = [2]

dims_const1 = tf.reverse(const1, dims)

print(dims_const1)

print(tf.shape(dims_const1))

tfutil.print_operation_value(dims_const1)

Tensor("ReverseV2_2:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 8  9 10 11]

   [ 4  5  6  7]

   [ 0  1  2  3]]

  [[20 21 22 23]

   [16 17 18 19]

   [12 13 14 15]]]]


tf.transpose(a, perm=None, name='transpose')


a를 전치합니다. perm에 따라 차원의 순서를 구성합니다.


반환되는 텐서의 차원 i는 입력되는 텐서의 차원 perm[i]에 해당합니다. 만약 perm이 주어지지 않을 경우, (n-1...0)으로 설정됩니다. 여기서 n은 입력 텐서의 랭크(rank)입니다. 따라서, 기본적으로 이 함수는 2-D 텐서가 입력될 경우 일반적인 행렬 전치를 수행합니다.


예시:

# 'x'는 [[1 2 3]

#        [4 5 6]]

tf.transpose(x) ==> [[1 4]

                     [2 5]

                     [3 6]]


# perm의 기본값과 동일한 경우

tf.transpose(x, perm=[1, 0]) ==> [[1 4]

                                  [2 5]

                                  [3 6]]


# 'perm'은 차원이 n > 2인 텐서일 경우 더 유용합니다.

# 'x'는   [[[1  2  3]

#           [4  5  6]]

#          [[7  8  9]

#           [10 11 12]]]

# 차원-0의 행렬들에 대해서 전치를 수행합니다.

tf.transpose(x, perm=[0, 2, 1]) ==> [[[1  4]

                                      [2  5]

                                      [3  6]]


                                     [[7 10]

                                      [8 11]

                                      [9 12]]]

인자:
  • aTensor.
  • perma의 차원들의 순열.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

전치된 Tensor.


출처: 텐서 변환


Tensorflow tf.transpose 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

'''

A=[2,3,4] matrix, using perm(1,0,2) will get B=[3,2,4]

 

Index = (0,1,2)

A     = [2,3,4]

Perm  = (1,0,2)

B     = (3,2,4)  --> Perm 1 from Index 1 (3), Perm 0 from Index 0 (2), Perm 2 from Index 2 (4) --> so get (3,2,4

'''

In [3]:

x = [[1, 2, 3, 4, 5, 6]]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 6), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3 4 5 6]]

In [4]:

perm = [1, 0]

trans_const1 = tf.transpose(const1, perm)

print(trans_const1)

print(tf.shape(trans_const1))

tfutil.print_operation_value(trans_const1)

Tensor("transpose:0", shape=(6, 1), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[1]

 [2]

 [3]

 [4]

 [5]

 [6]]

In [5]:

perm = [0, 1]

trans_const1 = tf.transpose(const1, perm)

print(trans_const1)

print(tf.shape(trans_const1))

tfutil.print_operation_value(trans_const1)

Tensor("transpose_1:0", shape=(1, 6), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2 3 4 5 6]]

In [6]:

x = [[1, 2, 3], [4, 5, 6]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [7]:

perm = [1, 0]

trans_const2 = tf.transpose(const2, perm)

print(trans_const2)

print(tf.shape(trans_const2))

tfutil.print_operation_value(trans_const2)

Tensor("transpose_2:0", shape=(3, 2), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[1 4]

 [2 5]

 [3 6]]

In [8]:

perm = [0, 1]

trans_const2 = tf.transpose(const2, perm)

print(trans_const2)

print(tf.shape(trans_const2))

tfutil.print_operation_value(trans_const2)

Tensor("transpose_3:0", shape=(2, 3), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [9]:

x = [[[ 123],

      [ 456]],

     [[ 789],

      [10, 11, 12]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2, 3), dtype=int32)

Tensor("Shape_6:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]]

In [10]:

perm = [1, 0, 2]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_4:0", shape=(2, 2, 3), dtype=int32)

Tensor("Shape_7:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 7  8  9]]

 [[ 4  5  6]

  [10 11 12]]]

In [11]:

perm = [2, 0, 1]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_5:0", shape=(3, 2, 2), dtype=int32)

Tensor("Shape_8:0", shape=(3,), dtype=int32)

[[[ 1  4]

  [ 7 10]]

 [[ 2  5]

  [ 8 11]]

 [[ 3  6]

  [ 9 12]]]

In [12]:

perm = [2, 1, 0]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_6:0", shape=(3, 2, 2), dtype=int32)

Tensor("Shape_9:0", shape=(3,), dtype=int32)

[[[ 1  7]

  [ 4 10]]

 [[ 2  8]

  [ 5 11]]

 [[ 3  9]

  [ 6 12]]]

In [13]:

perm = [1, 2, 0]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_7:0", shape=(2, 3, 2), dtype=int32)

Tensor("Shape_10:0", shape=(3,), dtype=int32)

[[[ 1  7]

  [ 2  8]

  [ 3  9]]

 [[ 4 10]

  [ 5 11]

  [ 6 12]]]

In [14]:

perm = [0, 2, 1]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_8:0", shape=(2, 3, 2), dtype=int32)

Tensor("Shape_11:0", shape=(3,), dtype=int32)

[[[ 1  4]

  [ 2  5]

  [ 3  6]]

 [[ 7 10]

  [ 8 11]

  [ 9 12]]]

In [15]:

perm = [0, 1, 2]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_9:0", shape=(2, 2, 3), dtype=int32)

Tensor("Shape_12:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]]


tf.extract_image_patches(images, padding, ksizes=None, strides=None, rates=None, name=None)


images에서 패치(patch)들을 추출하여 출력의 "depth" 차원에 넣습니다.

인자:
  • imagesTensor. 자료형이 float32float64int32int64uint8int16int8uint16half 중 하나여야 합니다. 구조(shape)가 [batch, in_rows, in_cols, depth]인 4-D 텐서입니다.
  • padding"SAME" 또는 "VALID"string. 사용할 패딩 알고리즘을 선택합니다.


    크기와 관련된 인자는 다음과 같이 정해집니다:

    ksizes = [1, ksize_rows, ksize_cols, 1]
    strides = [1, strides_rows, strides_cols, 1]
    rates = [1, rates_rows, rates_cols, 1]
  • ksizesint들의 리스트. 기본값은 []images의 각 차원에 대한 슬라이딩 윈도우의 크기를 지정합니다. (선택사항)

  • stridesint들의 리스트. 기본값은 []. 길이 4의 1-D 텐서. 이미지에서 추출할 두 patch 사이의 중심 거리를 지정합니다. [1, stride_rows, stride_cols, 1]와 같은 형태여야 합니다. (선택사항)
  • ratesint들의 리스트. 기본값은 []. 길이 4의 1-D 텐서. 입력의 스트라이드로, 입력에서 두 연속된 patch 샘플들이 얼마나 멀리 떨어져 있어야 할 지 지정합니다. [1, rate_rows, rate_cols, 1]와 같은 형태여야 합니다. (선택사항) patch를 추출할 때 patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)으로 놓고 공간적으로 rates의 인자로 부차추출(subsampling)하는 것과 동일합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

images와 자료형이 같은 Tensor. 구조(shape)가 [batch, out_rows, out_cols, ksize_rows * ksize_cols * depth]인 4-D 텐서입니다. 크기가 ksize_rows x ksize_cols x depth인 "depth" 차원에서 벡터화된 이미지 패치(patch)들을 포함합니다.


출처: 텐서 변환


Tensorflow tf.extract_image_patches 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

n = 10

# images is a 1 x 10 x 10 x 1 array that contains the numbers 1 through 100 in order

images = [[[[x * n + y + 1] for y in range(n)] for x in range(n)]]

 

const1 = tf.constant(np.array(images), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 10, 10, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[  1]

   [  2]

   [  3]

   [  4]

   [  5]

   [  6]

   [  7]

   [  8]

   [  9]

   [ 10]]

  [[ 11]

   [ 12]

   [ 13]

   [ 14]

   [ 15]

   [ 16]

   [ 17]

   [ 18]

   [ 19]

   [ 20]]

……………

  [[ 91]

   [ 92]

   [ 93]

   [ 94]

   [ 95]

   [ 96]

   [ 97]

   [ 98]

   [ 99]

   [100]]]]

In [3]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (1 x 1 x 1 ) = 1

# ksizes: raws: [1] col: [1]

ksizes = [1, 1, 1, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[  1]

   [  4]

   [  7]

   [ 10]]

  [[ 31]

   [ 34]

   [ 37]

   [ 40]]

  [[ 61]

   [ 64]

   [ 67]

   [ 70]]

  [[ 91]

   [ 94]

   [ 97]

   [100]]]]

In [4]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (1 x 2 x 1 ) = 2

# ksizes: raws: [1, 2]  col: [1, 2]

ksizes = [1, 1, 2, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_1:0", shape=(1, 4, 3, 2), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[ 1  2]

   [ 4  5]

   [ 7  8]]

  [[31 32]

   [34 35]

   [37 38]]

  [[61 62]

   [64 65]

   [67 68]]

  [[91 92]

   [94 95]

   [97 98]]]]

In [5]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (1 x 3 x 1 ) = 3

# ksizes: raws: [1, 2, 3]   col: [1, 2, 3]

ksizes = [1, 1, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_2:0", shape=(1, 4, 3, 3), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]

   [ 7  8  9]]

  [[31 32 33]

   [34 35 36]

   [37 38 39]]

  [[61 62 63]

   [64 65 66]

   [67 68 69]]

  [[91 92 93]

   [94 95 96]

   [97 98 99]]]]

In [6]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (2 x 3 x 1 ) = 6 -> [ 1  2  3 11 12 13] ..

# ksizes: raws: [1  2  3 ]   col: [1  2  3 11 12 13]

ksizes = [1, 2, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_3:0", shape=(1, 3, 3, 6), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13]

   [ 4  5  6 14 15 16]

   [ 7  8  9 17 18 19]]

  [[31 32 33 41 42 43]

   [34 35 36 44 45 46]

   [37 38 39 47 48 49]]

  [[61 62 63 71 72 73]

   [64 65 66 74 75 76]

   [67 68 69 77 78 79]]]]

In [7]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# ksizes: raws: [1  2  3 ]   col: [1  2  3 11 12 13 21 22 23]

ksizes = [1, 3, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_4:0", shape=(1, 3, 3, 9), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 4  5  6 14 15 16 24 25 26]

   [ 7  8  9 17 18 19 27 28 29]]

  [[31 32 33 41 42 43 51 52 53]

   [34 35 36 44 45 46 54 55 56]

   [37 38 39 47 48 49 57 58 59]]

  [[61 62 63 71 72 73 81 82 83]

   [64 65 66 74 75 76 84 85 86]

   [67 68 69 77 78 79 87 88 89]]]]

In [8]:

# strides Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# strides: raws: [1, 4, 7]   col: [1, 31, 61]

ksizes = [1, 3, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_5:0", shape=(1, 3, 3, 9), dtype=int32)

Tensor("Shape_6:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 4  5  6 14 15 16 24 25 26]

   [ 7  8  9 17 18 19 27 28 29]]

  [[31 32 33 41 42 43 51 52 53]

   [34 35 36 44 45 46 54 55 56]

   [37 38 39 47 48 49 57 58 59]]

  [[61 62 63 71 72 73 81 82 83]

   [64 65 66 74 75 76 84 85 86]

   [67 68 69 77 78 79 87 88 89]]]]

In [9]:

# strides Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# strides: raws: [1, 4, 7]   col: [1, 21, 41, 61]

ksizes = [1, 3, 3, 1]

strides = [1, 2, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_6:0", shape=(1, 4, 3, 9), dtype=int32)

Tensor("Shape_7:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 4  5  6 14 15 16 24 25 26]

   [ 7  8  9 17 18 19 27 28 29]]

  [[21 22 23 31 32 33 41 42 43]

   [24 25 26 34 35 36 44 45 46]

   [27 28 29 37 38 39 47 48 49]]

  [[41 42 43 51 52 53 61 62 63]

   [44 45 46 54 55 56 64 65 66]

   [47 48 49 57 58 59 67 68 69]]

  [[61 62 63 71 72 73 81 82 83]

   [64 65 66 74 75 76 84 85 86]

   [67 68 69 77 78 79 87 88 89]]]]

In [10]:

# strides Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# strides: raws: [1, 3, 5, 7]   col: [1, 31, 61]

ksizes = [1, 3, 3, 1]

strides = [1, 3, 2, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_7:0", shape=(1, 3, 4, 9), dtype=int32)

Tensor("Shape_8:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 3  4  5 13 14 15 23 24 25]

   [ 5  6  7 15 16 17 25 26 27]

   [ 7  8  9 17 18 19 27 28 29]]

  [[31 32 33 41 42 43 51 52 53]

   [33 34 35 43 44 45 53 54 55]

   [35 36 37 45 46 47 55 56 57]

   [37 38 39 47 48 49 57 58 59]]

  [[61 62 63 71 72 73 81 82 83]

   [63 64 65 73 74 75 83 84 85]

   [65 66 67 75 76 77 85 86 87]

   [67 68 69 77 78 79 87 88 89]]]]

In [11]:

# We generate four outputs as follows:

# 1. 3x3 patches with stride length 5

ksizes = [1, 3, 3, 1]

strides = [1, 5, 5, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_8:0", shape=(1, 2, 2, 9), dtype=int32)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 6  7  8 16 17 18 26 27 28]]

  [[51 52 53 61 62 63 71 72 73]

   [56 57 58 66 67 68 76 77 78]]]]

In [12]:

# 2. Same as above, but the rate is increased to 2

ksizes = [1, 3, 3, 1]

strides = [1, 5, 5, 1]

rates = [1, 2, 2, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_9:0", shape=(1, 2, 2, 9), dtype=int32)

Tensor("Shape_10:0", shape=(4,), dtype=int32)

[[[[  1   3   5  21  23  25  41  43  45]

   [  6   8  10  26  28  30  46  48  50]]

  [[ 51  53  55  71  73  75  91  93  95]

   [ 56  58  60  76  78  80  96  98 100]]]]

In [13]:

# 3. 4x4 patches with stride length 7; only one patch should be generated

ksizes = [1, 4, 4, 1]

strides = [1, 7, 7, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_10:0", shape=(1, 1, 1, 16), dtype=int32)

Tensor("Shape_11:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4 11 12 13 14 21 22 23 24 31 32 33 34]]]]

In [14]:

# 4. Same as above, but with padding set to 'SAME'

ksizes = [1, 4, 4, 1]

strides = [1, 7, 7, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='SAME')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_11:0", shape=(1, 2, 2, 16), dtype=int32)

Tensor("Shape_12:0", shape=(4,), dtype=int32)

[[[[  1   2   3   4  11  12  13  14  21  22  23  24  31  32  33  34]

   [  8   9  10   0  18  19  20   0  28  29  30   0  38  39  40   0]]

  [[ 71  72  73  74  81  82  83  84  91  92  93  94   0   0   0   0]

   [ 78  79  80   0  88  89  90   0  98  99 100   0   0   0   0   0]]]]


tf.space_to_batch(input, paddings, block_size, name=None)


타입 T의 4-D 텐서에 대한 SpaceToBatch 함수입니다.


텐서에 제로 패딩을 붙이고 공간적인 데이터의 블록을 batch로 재배열합니다. 구체적으로, 이 함수는 입력 텐서의 height와 width 차원이 batch 차원으로 옮겨진 복사본을 반환합니다. 제로 패딩이 행해진 뒤, 입력 텐서의 height와 width 값 모두 블록 크기로 나눌 수 있어야 합니다.

인자:
  • input: 구조(shape)가 [batch, height, width, depth]인 4-D Tensor.
  • paddingsint32형 2-D Tensor. 구조(shape)가 [2, 2]이며, 음이 아닌 정수로 구성됩니다. 입력을 공간 차원에서 어떻게 패딩할 것인지에 대해 다음과 같은 형태로 지정합니다.

    paddings = [[pad_top, pad_bottom], [pad_left, pad_right]]

    입력 텐서에서 패딩이 이루어지면 다음과 같은 공간 차원들을 가지게 됩니다.

    height_pad = pad_top + height + pad_bottom
    width_pad = pad_left + width + pad_right

    block_size는 1보다 커야 합니다. 이는 블록의 크기를 지정합니다.


    • height와 width 차원에서 block_size x block_size의 크기를 가지는 블록들은 각 위치에서 batch 차원으로 재배열됩니다.
    • 출력 텐서의 배치(batch)는 batch * block_size * block_size와 같습니다.
    • block_size가 height_pad와 width_pad의 약수여야 합니다.


      출력 텐서의 구조는 다음과 같습니다.

      [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

  • block_sizeint.


  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.space_to_batch 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1], [2]], [[3], [4]]]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [3]:

# return: [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

# paddings = [[pad_top, pad_bottom], [pad_left, pad_right]]

# height_pad = pad_top + height + pad_bottom

# width_pad = pad_left + width + pad_right

# blocksize = Both height_pad and width_pad must be divisible by block_size.

paddings = [[0, 0],[0, 0]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [4]:

paddings = [[0, 0],[0, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_1:0", shape=(1, 2, 3, 1), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[1]

   [2]

   [0]]

  [[3]

   [4]

   [0]]]]

In [5]:

paddings = [[0, 0],[1, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_2:0", shape=(1, 2, 4, 1), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[0]

   [1]

   [2]

   [0]]

  [[0]

   [3]

   [4]

   [0]]]]

In [6]:

paddings = [[0, 1],[1, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_3:0", shape=(1, 3, 4, 1), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[0]

   [1]

   [2]

   [0]]

  [[0]

   [3]

   [4]

   [0]]

  [[0]

   [0]

   [0]

   [0]]]]

In [7]:

paddings = [[1, 1],[1, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_4:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[0]

   [0]

   [0]

   [0]]

  [[0]

   [1]

   [2]

   [0]]

  [[0]

   [3]

   [4]

   [0]]

  [[0]

   [0]

   [0]

   [0]]]]

In [8]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_5:0", shape=(4, 1, 1, 1), dtype=int32)

Tensor("Shape_6:0", shape=(4,), dtype=int32)

[[[[1]]]

 [[[2]]]

 [[[3]]]

 [[[4]]]]

In [9]:

# [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

# blocksize = Both height_pad and width_pad must be divisible by block_size.

paddings = [[0, 0],[1, 1]]

blocksize = 2

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_6:0", shape=(4, 1, 2, 1), dtype=int32)

Tensor("Shape_7:0", shape=(4,), dtype=int32)

[[[[0]

   [2]]]

 [[[1]

   [0]]]

 [[[0]

   [4]]]

 [[[3]

   [0]]]]

In [10]:

# [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

# blocksize = Both height_pad and width_pad must be divisible by block_size.

paddings = [[1, 1],[1, 1]]

blocksize = 2

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_7:0", shape=(4, 2, 2, 1), dtype=int32)

Tensor("Shape_8:0", shape=(4,), dtype=int32)

[[[[0]

   [0]]

  [[0]

   [4]]]

 [[[0]

   [0]]

  [[3]

   [0]]]

 [[[0]

   [2]]

  [[0]

   [0]]]

 [[[1]

   [0]]

  [[0]

   [0]]]]

In [11]:

x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(1, 2, 2, 3), dtype=int32)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]]

  [[ 7  8  9]

   [10 11 12]]]]

In [12]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const2 = tf.space_to_batch(const2, paddings, blocksize)

print(stb_const2)

print(tf.shape(stb_const2))

tfutil.print_operation_value(stb_const2)

Tensor("SpaceToBatchND_8:0", shape=(4, 1, 1, 3), dtype=int32)

Tensor("Shape_10:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]]]

 [[[ 4  5  6]]]

 [[[ 7  8  9]]]

 [[[10 11 12]]]]

In [13]:

x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]], [[9], [10], [11], [12]], [[13], [14], [15], [16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_11:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]

In [14]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const3 = tf.space_to_batch(const3, paddings, blocksize)

print(stb_const3)

print(tf.shape(stb_const3))

tfutil.print_operation_value(stb_const3)

Tensor("SpaceToBatchND_9:0", shape=(4, 2, 2, 1), dtype=int32)

Tensor("Shape_12:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]

  [[ 9]

   [11]]]

 [[[ 2]

   [ 4]]

  [[10]

   [12]]]

 [[[ 5]

   [ 7]]

  [[13]

   [15]]]

 [[[ 6]

   [ 8]]

  [[14]

   [16]]]]

In [15]:

x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]]], [[[9], [10], [11], [12]], [[13], [14], [15], [16]]]]

const4 = tf.constant(np.array(x), dtype=tf.int32)

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(2, 2, 4, 1), dtype=int32)

Tensor("Shape_13:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]]

 [[[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]

In [16]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const4 = tf.space_to_batch(const4, paddings, blocksize)

print(stb_const4)

print(tf.shape(stb_const4))

tfutil.print_operation_value(stb_const4)

Tensor("SpaceToBatchND_10:0", shape=(8, 1, 2, 1), dtype=int32)

Tensor("Shape_14:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]]

 [[[ 9]

   [11]]]

 [[[ 2]

   [ 4]]]

 [[[10]

   [12]]]

 [[[ 5]

   [ 7]]]

 [[[13]

   [15]]]

 [[[ 6]

   [ 8]]]

 [[[14]

   [16]]]]


tf.batch_to_space(input, crops, block_size, name=None)


타입 T의 4-D 텐서에 대한 BatchToSpace 함수입니다.


배치(batch)의 데이터를 공간적인 데이터의 블록으로 재배열하고 자릅니다. SpaceToBatch 함수의 역과정에 해당합니다. 더 구체적으로, 이 함수는 input 텐서의 batch 차원의 값들이 height와 width 차원의 공간적인 블록으로 이동된 후, height 차원과 width 차원을 따라 잘린 텐서를 반환합니다.

인자:
  • input: 4-D Tensor[batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]의 구조(shape)를 가집니다. 입력 텐서의 배치(batch) 크기는 block_size * block_size의 배수여야 합니다.
  • cropsint32형 구조 [2, 2]의 2-D 텐서. 음이 아닌 정수로 구성됩니다. 중간 결과에서 공간 차원을 따라 몇 개의 원소를 잘라낼 것인지를 다음과 같이 결정합니다.

    crops = [[crop_top, crop_bottom], [crop_left, crop_right]]
  • block_sizeint.

  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 구조 [batch, height, width, depth]인 4-D Tensor.

height = height_pad - crop_top - crop_bottom
width = width_pad - crop_left - crop_right

을 만족합니다. block_size는 1보다 커야 합니다.


출처: 텐서 변환


Tensorflow tf.batch_to_space 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1]]], [[[2]]], [[[3]]], [[[4]]]]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(4, 1, 1, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1]]]

 [[[2]]]

 [[[3]]]

 [[[4]]]]

In [3]:

# crops = [[crop_top, crop_bottom], [crop_left, crop_right]]

# [batch, height, width, depth]

# height = height_pad - crop_top - crop_bottom

# width = width_pad - crop_left - crop_right

 

corps = [[0, 0],[0, 1]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND:0", shape=(4, 1, 0, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[]

In [4]:

corps = [[0, 0],[0, 1]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_1:0", shape=(4, 1, 0, 1), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[]

In [5]:

corps = [[0, 1],[0, 0]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_2:0", shape=(4, 0, 1, 1), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[]

In [6]:

corps = [[1, 0],[0, 0]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_3:0", shape=(4, 0, 1, 1), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[]

In [7]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_4:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [8]:

corps = [[0, 0],[1, 1]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_5:0", shape=(1, 2, 0, 1), dtype=int32)

Tensor("Shape_6:0", shape=(4,), dtype=int32)

[]

In [9]:

corps = [[1, 1],[0, 0]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_6:0", shape=(1, 0, 2, 1), dtype=int32)

Tensor("Shape_7:0", shape=(4,), dtype=int32)

[]

In [10]:

corps = [[1, 1],[1, 1]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_7:0", shape=(1, 0, 0, 1), dtype=int32)

Tensor("Shape_8:0", shape=(4,), dtype=int32)

[]

In [11]:

x = [[[[ 123]]],

 [[[ 456]]],

 [[[ 789]]],

 [[[10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(4, 1, 1, 3), dtype=int32)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]]]

 [[[ 4  5  6]]]

 [[[ 7  8  9]]]

 [[[10 11 12]]]]

In [12]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_8:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_10:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [13]:

x = [[[[1], [3]], [[9], [11]]],

     [[[2], [4]], [[10], [12]]],

     [[[5], [7]], [[13], [15]]],

     [[[6], [8]], [[14], [16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(4, 2, 2, 1), dtype=int32)

Tensor("Shape_11:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]

  [[ 9]

   [11]]]

 [[[ 2]

   [ 4]]

  [[10]

   [12]]]

 [[[ 5]

   [ 7]]

  [[13]

   [15]]]

 [[[ 6]

   [ 8]]

  [[14]

   [16]]]]

In [14]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const3 = tf.batch_to_space(const3, corps, blocksize)

print(bts_const3)

print(tf.shape(bts_const3))

tfutil.print_operation_value(bts_const3)

Tensor("BatchToSpaceND_9:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_12:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]

In [15]:

x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]],

     [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]]

const4 = tf.constant(np.array(x), dtype=tf.int32)

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(8, 1, 2, 1), dtype=int32)

Tensor("Shape_13:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]]

 [[[ 9]

   [11]]]

 [[[ 2]

   [ 4]]]

 [[[10]

   [12]]]

 [[[ 5]

   [ 7]]]

 [[[13]

   [15]]]

 [[[ 6]

   [ 8]]]

 [[[14]

   [16]]]]

In [16]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const4 = tf.batch_to_space(const4, corps, blocksize)

print(bts_const4)

print(tf.shape(bts_const4))

tfutil.print_operation_value(bts_const4)

Tensor("BatchToSpaceND_10:0", shape=(2, 2, 4, 1), dtype=int32)

Tensor("Shape_14:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]]

 [[[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]


tf.space_to_depth(input, block_size, name=None)


타입 T의 4-D 텐서에 대한 SpaceToDepth 함수입니다.


공간적인 데이터의 블록을 depth로 재배열합니다. 구체적으로, 입력 텐서의 height와 width 차원의 데이터를 depth 차원으로 옮깁니다. block_size는 입력 텐서의 블록 사이즈와 데이터가 어떻게 옮겨질지를 지정합니다.

  • 크기 block_size x block size의 블록이 각 위치의 depth로 재배열됩니다.
  • 출력 텐서의 depth 차원의 크기는 input_depth * block_size * block_size입니다.
  • 입력 텐서의 height와 width는 block_size의 배수여야 합니다.

즉, 만약 입력의 구조(shape)가[batch, height, width, depth]이면, 출력 텐서의 구조는 [batch, height/block_size, width/block_size, epth*block_size*block_size]이 됩니다.


이 함수는 입력 텐서의 랭크(rank)가 4여야 하며, block_size가 1 이상이어야 하고 height와 width의 약수여야 합니다.


이 함수는 합성곱 연산 사이의 활성화에서 데이터를 그대로 유지한 채로 크기를 변경시키는 때 유용합니다(예로, 풀링 대신 사용할 수 있습니다). 합성곱 연산만으로 이루어진 모델의 훈련에도 유용합니다.


예로, 구조 [1, 2, 2, 1]의 입력과 block_size = 2가 주어진 경우,

x = [[[[1], [2]],
      [[3], [4]]]]

이 함수는 다음과 같은 구조 [1, 1, 1, 4]의 텐서를 반환합니다.

[[[[1, 2, 3, 4]]]]

여기서, 입력은 크기 1의 배치를 가지며, 각 배치는 구조 [2, 2, 1]로 배열된 원소를 가집니다. 출력에서 각각은 width와 height가 모두 1이고, 4 채널의 depth를 가지도록 배열되며, 따라서 각각은 구조 [1, 1, 4]를 가지게 됩니다.


더 큰 depth를 가지는 입력 텐서의 경우(여기서는 [1, 2, 2, 3])를 봅시다.

x = [[[[1, 2, 3], [4, 5, 6]],
      [[7, 8, 9], [10, 11, 12]]]]

block_size에 2를 넣어 이 함수를 적용할 경우, 구조 [1, 1, 1, 12]인 텐서

[[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]

를 출력합니다. 비슷하게, block_size가 2이고 입력의 구조가 [1 4 4 1]인 경우,

x = [[[[1],   [2],  [5],  [6]],

      [[3],   [4],  [7],  [8]],

      [[9],  [10], [13],  [14]],

      [[11], [12], [15],  [16]]]]

이 함수는 구조 [1 2 2 4]인 다음 텐서를 반환합니다.

x = [[[[1, 2, 3, 4],
       [5, 6, 7, 8]],
      [[9, 10, 11, 12],
       [13, 14, 15, 16]]]]
인자:
  • inputTensor.
  • block_sizeint. 공간 블록의 크기를 지정합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.space_to_depth 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1], [2]],

      [[3], [4]]]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [3]:

# input: [batch, height, width, depth]

# output: [batch, height/block_size, width/block_size, depth*block_size*block_size]

blocksize = 2

std_const1 = tf.space_to_depth(const1, blocksize)

print(std_const1)

print(tf.shape(std_const1))

tfutil.print_operation_value(std_const1)

Tensor("SpaceToDepth:0", shape=(1, 1, 1, 4), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[1 2 3 4]]]]

In [4]:

x = [[[[1, 2, 3], [4, 5, 6]],

      [[7, 8, 9], [10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(1, 2, 2, 3), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]]

  [[ 7  8  9]

   [10 11 12]]]]

In [5]:

blocksize = 2

std_const2 = tf.space_to_depth(const2, blocksize)

print(std_const2)

print(tf.shape(std_const2))

tfutil.print_operation_value(std_const2)

Tensor("SpaceToDepth_1:0", shape=(1, 1, 1, 12), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4  5  6  7  8  9 10 11 12]]]]

In [6]:

x = [[[[1],   [2],  [5],  [6]],

      [[3],   [4],  [7],  [8]],

      [[9],  [10], [13],  [14]],

      [[11], [12], [15],  [16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 5]

   [ 6]]

  [[ 3]

   [ 4]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [13]

   [14]]

  [[11]

   [12]

   [15]

   [16]]]]

In [7]:

blocksize = 2

std_const3 = tf.space_to_depth(const3, blocksize)

print(std_const3)

print(tf.shape(std_const3))

tfutil.print_operation_value(std_const3)

Tensor("SpaceToDepth_2:0", shape=(1, 2, 2, 4), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4]

   [ 5  6  7  8]]

  [[ 9 10 11 12]

   [13 14 15 16]]]]


tf.depth_to_space(input, block_size, name=None)


타입 T의 4-D 텐서에 대한 DepthToSpace 함수입니다.


depth의 데이터를 공간적인 데이터의 블록으로 재배열합니다. SpaceToDepth 함수의 역과정과 같습니다. 구체적으로, 이 함수는 depth 차원의 값들을 height와 width 차원들의 공간적인 블록으로 이동시킵니다. block_size는 입력의 블록 크기와 데이터가 어떻게 이동될지를 지정합니다.

  • depth에서 block_size * block_size 크기의 데이터가 block_size x block_size의 블록으로 재배열됩니다.
  • 출력 텐서의 width의 크기는 input_depth * block_size이며, height의 크기는 input_height * block_size 입니다.
  • 입력 텐서의 depth는 block_size * block_size의 배수여야 합니다.

즉, 만약 입력의 구조(shape)가 [batch, height, width, depth]라면, 출력 텐서의 구조는[batch, height*block_size, width*block_size, depth/(block_size*block_size)]와 같습니다.


이 함수는 입력 텐서의 랭크(rank)가 4여야 하며, block_size는 1 이상이고 block_size * block_size가 입력 텐서의 depth의 약수여야 합니다.


이 함수는 합성곱 연산 사이의 활성화에서 데이터를 그대로 유지한 채로 크기를 변경시키는 때 유용합니다(예로, 풀링 대신 사용할 수 있습니다). 합성곱 연산만으로 이루어진 모델의 훈련에도 유용합니다.


예로, 구조 [1, 1, 1, 4]의 입력과 block_size = 2가 주어진 경우,

x = [[[[1, 2, 3, 4]]]]

이 함수는 다음과 같은 구조 [1, 2, 2, 1]의 텐서를 반환합니다.

  [[[[1], [2]],
     [[3], [4]]]]

여기서, 입력은 크기 1의 배치를 가지며, 각 배치는 구조 [1, 1, 4]로 배열된 원소를 가집니다. 출력에서 각각은 2x2 원소에 1 채널의 (1 = 4 / (block_size * block_size)depth를 가지도록 배열되며, 따라서 각각은 구조 [2, 2, 1]을 가지게 됩니다.


더 큰 depth를 가지는 입력 텐서의 경우(여기서는 [1, 1, 1, 12])를 봅시다.

x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]

block_size에 2를 넣어 이 함수를 적용할 경우, 구조 [1, 2, 2, 3]인 텐서

   [[[[1, 2, 3], [4, 5, 6]],
     [[7, 8, 9], [10, 11, 12]]]]

를 출력합니다. 비슷하게, block_size가 2이고 입력의 구조가 [1 2 2 4]인 경우,

x =  [[[[1, 2, 3, 4],
       [5, 6, 7, 8]],
      [[9, 10, 11, 12],
       [13, 14, 15, 16]]]]

이 함수는 구조 [1 4 4 1]인 다음 텐서를 반환합니다.

x = [[ [1],   [2],  [5],  [6]],
     [ [3],   [4],  [7],  [8]],
     [ [9],  [10], [13],  [14]],
     [ [11], [12], [15],  [16]]]
인자:
  • inputTensor.
  • block_sizeint. 공간 블록의 크기를 지정합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.depth_to_space 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1, 2, 3, 4]]]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 1, 1, 4), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1 2 3 4]]]]

In [3]:

blocksize = 2

dts_const1 = tf.depth_to_space(const1, blocksize)

print(dts_const1)

print(tf.shape(dts_const1))

tfutil.print_operation_value(dts_const1)

Tensor("DepthToSpace:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [4]:

x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(1, 1, 1, 12), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4  5  6  7  8  9 10 11 12]]]]

In [5]:

blocksize = 2

dts_const2 = tf.depth_to_space(const2, blocksize)

print(dts_const2)

print(tf.shape(dts_const2))

tfutil.print_operation_value(dts_const2)

Tensor("DepthToSpace_1:0", shape=(1, 2, 2, 3), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]]

  [[ 7  8  9]

   [10 11 12]]]]

In [6]:

x =  [[[[1, 2, 3, 4],

       [5, 6, 7, 8]],

      [[9, 10, 11, 12],

       [13, 14, 15, 16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(1, 2, 2, 4), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4]

   [ 5  6  7  8]]

  [[ 9 10 11 12]

   [13 14 15 16]]]]

In [7]:

blocksize = 2

dts_const3 = tf.depth_to_space(const3, blocksize)

print(dts_const3)

print(tf.shape(dts_const3))

tfutil.print_operation_value(dts_const3)

Tensor("DepthToSpace_2:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 5]

   [ 6]]

  [[ 3]

   [ 4]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [13]

   [14]]

  [[11]

   [12]

   [15]

   [16]]]]


tf.gather(params, indices, validate_indices=None, name=None)


indices에 따라 params에서 슬라이스를 모읍니다.


indices는 임의 차원의 정수 텐서여야 합니다(주로 0-D 또는 1-D). 구조(shape)가 indices.shape + params.shape[1:]인 출력 텐서를 생성합니다.

# Scalar indices
output[:, ..., :] = params[indices, :, ... :]

# Vector indices
output[i, :, ..., :] = params[indices[i], :, ... :]

# Higher rank indices
output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :]

만약 indices이 순열이고 len(indices) == params.shape[0]이라면, 이 함수는 그에 따라 params를 재배열합니다.


 
인자:
  • paramsTensor.
  • indicesint32형 또는 int64형 Tensor.
  • validate_indicesbool. 기본값은 True. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

params와 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.gather 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[1, 2, 3],

     [4, 5, 6], 

     [7, 8, 9]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3, 3), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [3]:

idx_const2 = tf.constant([1, 0, 2])

print(idx_const2)

print(tf.shape(idx_const2))

tfutil.print_constant(idx_const2)

Tensor("Const_1:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 0 2]

In [4]:

idx_flattened = tf.range(0, const1.shape[0]) * const1.shape[1] + idx_const2

print(idx_flattened)

print(tf.shape(idx_flattened))

tfutil.print_constant(idx_flattened)

Tensor("add:0", shape=(3,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[1 3 8]

In [5]:

# partial code 1

print(const1.shape[0])

tmp1 = tf.range(0, const1.shape[0])

print(tmp1)

print(tf.shape(tmp1))

tfutil.print_constant(tmp1)

3

Tensor("range_1:0", shape=(3,), dtype=int32)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[0 1 2]

In [6]:

# partial code 2

print(const1.shape[1])

tmp2 = tf.range(0, const1.shape[0]) * const1.shape[1]

print(tmp2)

print(tf.shape(tmp2))

tfutil.print_constant(tmp2)

3

Tensor("mul_1:0", shape=(3,), dtype=int32)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[0 3 6]

In [7]:

# partial code 3

tmp3 = tmp2 + idx_const2

print(tmp3)

print(tf.shape(tmp3))

tfutil.print_constant(tmp3)

Tensor("add_1:0", shape=(3,), dtype=int32)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[1 3 8]

In [8]:

params = tf.reshape(x, [-1]) 

print(params)

print(tf.shape(params))

tfutil.print_constant(params)

Tensor("Reshape:0", shape=(9,), dtype=int32)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[1 2 3 4 5 6 7 8 9]

In [9]:

gather_const1 = tf.gather(params,         # flatten input

              idx_flattened)  # use flattened indices

print(gather_const1)

print(tf.shape(gather_const1))

tfutil.print_constant(gather_const1)

Tensor("Gather:0", shape=(3,), dtype=int32)

Tensor("Shape_7:0", shape=(1,), dtype=int32)

[2 4 9]


tf.gather_nd(params, indices, name=None)


indices에 따라 params에서 값들을 모읍니다.


indices는 params의 인덱스들을 포함하는 정수형 텐서입니다. 구조(shape)는 [d_0, ..., d_N, R]이어야 하고, 여기서 R은 params의 랭크(rank)입니다. indices의 가장 안쪽의 차원들(길이 R의)는 params의 인덱스들에 해당합니다.


출력 텐서의 구조(shape)는 [d_0, ..., d_{n-1}]이고, 다음을 만족합니다.

output[i, j, k, ...] = params[indices[i, j, k, ..., :]]

예로, indices에 대해서 다음과 같습니다.

output[i] = params[indices[i, :]]
인자:
  • paramsR-D Tensor. 값들을 모을 Tensor입니다.
  • indicesint32형 또는 int64형 (N+1)-D Tensor. 구조(shape)가 [d_0, ..., d_N, R]이어야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

params와 같은 자료형의 N-D Tensorindices에 따라 주어진 인덱스들로부터 params의 값들을 모은 텐서입니다.


출처: 텐서 변환


Tensorflow tf.gather_nd 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [d_0, ..., d_{Q-2}, params.shape[K], ..., params.shape[P-1]].

x = [['a', 'b'], ['c', 'd']]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 2), dtype=string)

Tensor("Shape:0", shape=(2,), dtype=int32)

[['a' 'b']

 ['c' 'd']]

In [3]:

# Simple indexing into a matrix:

indices = [[0, 0], [1, 1]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd:0", shape=(2,), dtype=string)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

['a' 'd']

In [4]:

# Slice indexing into a matrix:

indices = [[1], [0]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd_1:0", shape=(2, 2), dtype=string)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[['c' 'd']

 ['a' 'b']]

In [5]:

# Batched indexing into a matrix:

indices = [[[0, 0]], [[0, 1]]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd_2:0", shape=(2, 1), dtype=string)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[['a']

 ['b']]

In [6]:

# Batched slice indexing into a matrix:

indices = [[[1]], [[0]]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd_3:0", shape=(2, 1, 2), dtype=string)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[['c' 'd']]

 [['a' 'b']]]

In [7]:

x = [[['a0', 'b0'], ['c0', 'd0']],

    [['a1', 'b1'], ['c1', 'd1']]]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 2, 2), dtype=string)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[['a0' 'b0']

  ['c0' 'd0']]

 [['a1' 'b1']

  ['c1' 'd1']]]

In [8]:

# Indexing into a 3-tensor:

indices = [[1]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_4:0", shape=(1, 2, 2), dtype=string)

Tensor("Shape_6:0", shape=(3,), dtype=int32)

[[['a1' 'b1']

  ['c1' 'd1']]]

In [9]:

indices = [[0, 1], [1, 0]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_5:0", shape=(2, 2), dtype=string)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[['c0' 'd0']

 ['a1' 'b1']]

In [10]:

indices = [[0, 0, 1], [1, 0, 1]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_6:0", shape=(2,), dtype=string)

Tensor("Shape_8:0", shape=(1,), dtype=int32)

['b0' 'b1']

In [11]:

# Batched indexing into a 3-tensor:

indices = [[[1]], [[0]]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_7:0", shape=(2, 1, 2, 2), dtype=string)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[['a1' 'b1']

   ['c1' 'd1']]]

 [[['a0' 'b0']

   ['c0' 'd0']]]]

In [12]:

indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_8:0", shape=(2, 2, 2), dtype=string)

Tensor("Shape_10:0", shape=(3,), dtype=int32)

[[['c0' 'd0']

  ['a1' 'b1']]

 [['a0' 'b0']

  ['c1' 'd1']]]

In [13]:

indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_9:0", shape=(2, 2), dtype=string)

Tensor("Shape_11:0", shape=(2,), dtype=int32)

[['b0' 'b1']

 ['d0' 'c1']]


tf.dynamic_partition(data, partitions, num_partitions, name=None)


partitions의 인덱스들을 이용해서 data를 num_partitions개의 텐서로 나눕니다.


각각의 크기 partitions.ndim인 인덱스 튜플 js에 대해, 슬라이스 data[js, ...]는 outputs[partitions[js]]의 부분이 됩니다. partitions[js] = i인 슬라이스는 outputs[i]에 js의 사전 순서대로 배열되고, outputs[i]의 첫 번째 차원은 partitions의 엔트리 중 i와 같은 것의 수입니다. 구체적으로,

outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:]

outputs[i] = pack([data[js, ...] for js if partitions[js] == i])

입니다. data.shape는 partitions.shape로 시작해야 합니다.


예시:

# 스칼라 분할

partitions = 1

num_partitions = 2

data = [10, 20]

outputs[0] = []  # Empty with shape [0, 2]

outputs[1] = [[10, 20]]


# 벡터 분할

partitions = [0, 0, 1, 1, 0]

num_partitions = 2

data = [10, 20, 30, 40, 50]

outputs[0] = [10, 20, 50]

outputs[1] = [30, 40]

 
인자:
  • dataTensor.
  • partitionsint32형 Tensor. 임의의 구조(shape)가 가능합니다. 범위 [0, num_partitions) 내의 인덱스들을 포함합니다.
  • num_partitionsint(>= 1). 분할의 수.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

num_partitions개 Tensor의 리스트.


출처: 텐서 변환


Tensorflow tf.dynamic_partition 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:]

# outputs[i] = pack([data[js, ...] for js if partitions[js] == i])

 

x = [10, 20]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[10 20]

In [3]:

# Scalar partitions.

partitions = 1

num_partitions = 2

dyp_const1 = tf.dynamic_partition(const1, partitions, num_partitions)

print(dyp_const1[0])

print(tf.shape(dyp_const1[0]))

tfutil.print_operation_value(dyp_const1[0])

Tensor("DynamicPartition:0", shape=(?, 2), dtype=int64)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[]

In [4]:

print(dyp_const1[1])

print(tf.shape(dyp_const1[1]))

tfutil.print_operation_value(dyp_const1[1])

Tensor("DynamicPartition:1", shape=(?, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[10 20]]

In [5]:

print(dyp_const1)

print(tf.shape(dyp_const1))

tfutil.print_operation_value(dyp_const1)

[<tf.Tensor 'DynamicPartition:0' shape=(?, 2) dtype=int64>, <tf.Tensor 'DynamicPartition:1' shape=(?, 2) dtype=int64>]

Tensor("Shape_3:0", shape=(3,), dtype=int32)

[array([], shape=(0, 2), dtype=int64), array([[10, 20]])]

In [6]:

x = [10, 20, 30, 40, 50]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(5,), dtype=int64)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[10 20 30 40 50]

In [7]:

# Vector partitions.

partitions = [0, 0, 1, 1, 0]

num_partitions = 2

dyp_const2 = tf.dynamic_partition(const2, partitions, num_partitions)

print(dyp_const2[0])

print(tf.shape(dyp_const2[0]))

tfutil.print_operation_value(dyp_const2[0])

Tensor("DynamicPartition_1:0", shape=(?,), dtype=int64)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[10 20 50]

In [8]:

print(dyp_const2[1])

print(tf.shape(dyp_const2[1]))

tfutil.print_operation_value(dyp_const2[1])

Tensor("DynamicPartition_1:1", shape=(?,), dtype=int64)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[30 40]

In [9]:

print(dyp_const2)

print(tf.shape(dyp_const2))

tfutil.print_operation_value(dyp_const2)

[<tf.Tensor 'DynamicPartition_1:0' shape=(?,) dtype=int64>, <tf.Tensor 'DynamicPartition_1:1' shape=(?,) dtype=int64>]

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[array([10, 20, 50]), array([30, 40])]


tf.dynamic_stitch(indices, data, name=None)


data 안의 텐서들 안의 값을 단일 텐서에 끼웁니다.

merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...]

를 만족하는 merged 텐서를 구성합니다. 예로, 만약 각각의 indices[m]이 스칼라이거나 벡터라면, 다음이 성립합니다.

# Scalar indices
merged[indices[m], ...] = data[m][...]

# Vector indices
merged[indices[m][i], ...] = data[m][i, ...]

각각의 data[i].shape는 해당하는 indices[i].shape로 시작해야 하며, data[i].shape의 나머지는 i에 대해서 일정해야 합니다. 즉, data[i].shape = indices[i].shape + constant이어야 합니다. 이 constant에 대해, 출력 텐서의 구조(shape)는

merged.shape = [max(indices)] + constant

입니다. 값들은 순서대로 합쳐집니다. 즉, 인덱스가 indices[m][i]와 indices[n][j] 모두에서 나타나고 (m,i) < (n,j)인 경우 슬라이스 data[n][j]가 합쳐진 결과에 나타납니다.


예시:

indices[0] = 6

indices[1] = [4, 1]

indices[2] = [[5, 2], [0, 3]]

data[0] = [61, 62]

data[1] = [[41, 42], [11, 12]]

data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]

merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42],

          [51, 52], [61, 62]]

 
인자:
  • indices: 2개 이상의 int32형 Tensor의 리스트.
  • data: 같은 자료형의 Tensor들의 리스트. indices의 텐서 개수와 리스트의 Tensor 수가 같아야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

data와 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.dynamic_stitch 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[1, 2], [3, 4]]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 2), dtype=int64)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]]

In [3]:

y = [1, 1]

row_to_add = tf.constant(np.array(y))

print(row_to_add)

print(tf.shape(row_to_add))

tfutil.print_constant(row_to_add)

Tensor("Const_1:0", shape=(2,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 1]

In [4]:

original_row = const1[0]

print(original_row)

print(tf.shape(original_row))

tfutil.print_constant(original_row)

Tensor("strided_slice:0", shape=(2,), dtype=int64)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[1 2]

In [5]:

updated_row = original_row + row_to_add

print(updated_row)

print(tf.shape(updated_row))

tfutil.print_operation_value(updated_row)

Tensor("add:0", shape=(2,), dtype=int64)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[2 3]

In [6]:

unchanged_indices = tf.range(tf.size(const1))

print(unchanged_indices)

print(tf.shape(unchanged_indices))

tfutil.print_operation_value(unchanged_indices)

Tensor("range:0", shape=(4,), dtype=int32)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[0 1 2 3]

In [7]:

changed_indices = tf.range(const1.get_shape()[0])

print(changed_indices)

print(tf.shape(changed_indices))

tfutil.print_operation_value(changed_indices)

Tensor("range_1:0", shape=(2,), dtype=int32)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[0 1]

In [8]:

a_flat = tf.reshape(const1, [-1])

print(a_flat)

print(tf.shape(a_flat))

tfutil.print_operation_value(a_flat)

Tensor("Reshape:0", shape=(4,), dtype=int64)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[1 2 3 4]

In [9]:

updated_a_flat = tf.dynamic_stitch([unchanged_indices, changed_indices], [a_flat, updated_row])

print(updated_a_flat)

print(tf.shape(updated_a_flat))

tfutil.print_operation_value(updated_a_flat)

Tensor("DynamicStitch:0", shape=(4,), dtype=int64)

Tensor("Shape_7:0", shape=(1,), dtype=int32)

[2 3 3 4]

In [10]:

updated_a = tf.reshape(updated_a_flat, const1.get_shape())

print(updated_a)

print(tf.shape(updated_a))

tfutil.print_operation_value(updated_a)

Tensor("Reshape_1:0", shape=(2, 2), dtype=int64)

Tensor("Shape_8:0", shape=(2,), dtype=int32)

[[2 3]

 [3 4]]

In [11]:

# Apply function (increments x_i) on elements for which a certain condition

# apply (x_i != -1 in this example).

x = [0.1, -1., 5.2, 4.3, -1., 7.4]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const_2:0", shape=(6,), dtype=float64)

Tensor("Shape_9:0", shape=(1,), dtype=int32)

[ 0.1 -1.   5.2  4.3 -1.   7.4]

In [12]:

condition_mask=tf.not_equal(x,tf.constant(-1.))

print(condition_mask)

print(tf.shape(condition_mask))

tfutil.print_constant(condition_mask)

Tensor("NotEqual:0", shape=(6,), dtype=bool)

Tensor("Shape_10:0", shape=(1,), dtype=int32)

[ True False  True  True False  True]

In [13]:

partitioned_data = tf.dynamic_partition(x,

    tf.cast(condition_mask, tf.int32) , 2)

print(partitioned_data)

print(tf.shape(partitioned_data))

[<tf.Tensor 'DynamicPartition:0' shape=(?,) dtype=float32>, <tf.Tensor 'DynamicPartition:1' shape=(?,) dtype=float32>]

Tensor("Shape_11:0", shape=(2,), dtype=int32)

In [14]:

partitioned_data[1] = partitioned_data[1] + 1.0

print(partitioned_data[1])

print(tf.shape(partitioned_data[1]))

tfutil.print_constant(partitioned_data[1])

Tensor("add_1:0", shape=(?,), dtype=float32)

Tensor("Shape_12:0", shape=(1,), dtype=int32)

[ 1.10000002  6.19999981  5.30000019  8.39999962]

In [15]:

condition_indices = tf.dynamic_partition(

    tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2)

print(condition_indices)

print(tf.shape(condition_indices))

[<tf.Tensor 'DynamicPartition_1:0' shape=(?,) dtype=int32>, <tf.Tensor 'DynamicPartition_1:1' shape=(?,) dtype=int32>]

Tensor("Shape_14:0", shape=(2,), dtype=int32)

In [16]:

ds_const1 = tf.dynamic_stitch(condition_indices, partitioned_data)

print(ds_const1)

print(tf.shape(ds_const1))

tfutil.print_constant(ds_const1)

Tensor("DynamicStitch_1:0", shape=(?,), dtype=float32)

Tensor("Shape_15:0", shape=(1,), dtype=int32)

[ 1.10000002 -1.          6.19999981  5.30000019 -1.          8.39999962]


tf.boolean_mask(tensor, mask, name='boolean_mask')


텐서에 불리언 마스크(boolean mask)를 적용합니다. NumPy의 tensor[mask]와 동일합니다.

# 1-D 예시
tensor = [0, 1, 2, 3]
mask = [True, False, True, False]
boolean_mask(tensor, mask) ==> [0, 2]

일반적으로 0 < dim(mask) = K <= dim(tensor)이고, mask의 구조(shape)는 tensor 구조의 첫 K 차원이 일치해야 합니다. 그렇게 되면 boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd] 을 만족하며, (i1,...,iK)는 i번째 mask의 i번째 True인 원소입니다(행 우선 순서).

인자:
  • tensor: N-D 텐서.
  • mask: K-D 불리언 텐서, K <= N이고, K는 정적으로(statically) 알려져 있어야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

mask에서 True인 값들에 대한 tensor의 원소들로 이루어진 텐서.

예외:
  • ValueError: 모양이 일치하지 않는 경우.
예시:
# 2-D 예시
tensor = [[1, 2], [3, 4], [5, 6]]
mask = [True, False, True]
boolean_mask(tensor, mask) ==> [[1, 2], [5, 6]]


출처: 텐서 변환


Tensorflow tf.boolean_mask 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [0, 1, 2, 3]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(4,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[0 1 2 3]

In [3]:

mask = np.array([True, False, True, False])

bm_const1 = tf.boolean_mask(const1, mask)

print(bm_const1)

print(tf.shape(bm_const1))

tfutil.print_operation_value(bm_const1)

Tensor("boolean_mask/Gather:0", shape=(?,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[0 2]

In [4]:

x = [[1, 2], [3, 4], [5, 6]]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]

 [5 6]]

In [5]:

mask = np.array([True, False, True])

bm_const2 = tf.boolean_mask(const2, mask)

print(bm_const2)

print(tf.shape(bm_const2))

tfutil.print_operation_value(bm_const2)

Tensor("boolean_mask_1/Gather:0", shape=(?, 2), dtype=int64)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2]

 [5 6]]


tf.one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)


One-hot 텐서를 반환합니다.


indices의 인덱스에 있는 위치는 on_value, 아닌 위치는 off_value의 값을 가집니다.

on_value와 off_value는 같은 자료형을 가져야 합니다. 만약 dtype이 주어진 경우, 그들은 dtype에 의해 정해진 자료형이어야 합니다.

만약 on_value가 주어지지 않으면, dtype형의 1이 기본값으로 정해집니다.

비슷하게 off_value가 주어지지 않은 경우 dtype 형의 0이 기본값입니다.

입력 indices가 랭크 N인 경우, 출력은 랭크 N+1을 가집니다. 새로운 축이 차원 axis에 추가됩니다(기본적으로 새 축은 끝에 추가됩니다).

만약 indices가 스칼라라면 출력의 구조(shape)는 길이 depth의 벡터가 됩니다.


만약 indices가 길이 features의 벡터라면, 출력의 구조는 다음과 같습니다.

features x depth if axis == -1
depth x features if axis == 0

만약 indices가 구조 [batch, features]의 행렬(또는 배치)이라면, 출력의 구조는 다음과 같습니다.

batch x features x depth if axis == -1
batch x depth x features if axis == 1
depth x batch x features if axis == 0

dtype가 주어지지 않은 경우, on_value 또는 off_value가 주어졌다면 그들로부터 자료형을 추측합니다. 만약 셋 모두 주어지지 않았다면 기본 자료형은 tf.float32형 입니다.


참고: 수가 아닌 출력 자료형이 요구되는 경우(tf.stringtf.bool 등), on_value와 off_value 모두 주어져야 합니다.

예시:

다음이 주어진 경우

indices = [0, 2, -1, 1]
depth = 3
on_value = 5.0
off_value = 0.0
axis = -1

출력은 다음의 [4 x 3]입니다.

output =
[5.0 0.0 0.0]  // one_hot(0)
[0.0 0.0 5.0]  // one_hot(2)
[0.0 0.0 0.0]  // one_hot(-1)
[0.0 5.0 0.0]  // one_hot(1)

다음이 주어진 경우

indices = [[0, 2], [1, -1]]
depth = 3
on_value = 1.0
off_value = 0.0
axis = -1

출력은 다음의 [2 x 2 x 3]입니다.

  output =
  [
    [1.0, 0.0, 0.0]  // one_hot(0)
    [0.0, 0.0, 1.0]  // one_hot(2)
  ][
    [0.0, 1.0, 0.0]  // one_hot(1)
    [0.0, 0.0, 0.0]  // one_hot(-1)
  ]

다음과 강티 on_value와 off_value의 기본값을 이용하는 경우,

  indices = [0, 1, 2]
  depth = 3

출력은 다음과 같습니다.

  output =
  [[1., 0., 0.],
   [0., 1., 0.],
   [0., 0., 1.]]
인자:
  • indices: 인덱스들의 Tensor.
  • depth: One-hot 차원의 깊이(depth)를 결정하는 스칼라 값.
  • on_valueindices[j] = i인 경우 채울 스칼라 값. (기본값: 1, 선택사항)
  • off_valueindices[j] != i인 경우 채울 스칼라 값. (기본값: 0, 선택사항)
  • axis: 채워질 축 (기본값: -1, 선택사항).
  • dtype: 출력 텐서의 자료형.
반환값:
  • output: One-hot 텐서.
예외:
  • TypeErroron_value 또는 off_value의 자료형이 dtype과 다른 경우
  • TypeErroron_value와 off_value의 자료형이 서로 다른 경우

출처: 텐서 변환


Tensorflow tf.one_hot 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [0, 1, 2]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[0 1 2]

In [3]:

depth = 3

oh_const1 = tf.one_hot(const1, depth)

print(oh_const1)

print(tf.shape(oh_const1))

tfutil.print_operation_value(oh_const1)

Tensor("one_hot:0", shape=(3, 3), dtype=float32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[ 1.  0.  0.]

 [ 0.  1.  0.]

 [ 0.  0.  1.]]

In [4]:

x = [0, 2, -1, 1]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(4,), dtype=int64)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[ 0  2 -1  1]

In [5]:

depth = 3

bm_const2 = tf.one_hot(const2, depth,

    on_value=5.0, off_value=0.0, axis=-1)

print(bm_const2)

print(tf.shape(bm_const2))

tfutil.print_operation_value(bm_const2)

Tensor("one_hot_1:0", shape=(4, 3), dtype=float32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[ 5.  0.  0.]

 [ 0.  0.  5.]

 [ 0.  0.  0.]

 [ 0.  5.  0.]]

In [6]:

x = [[0, 2], [1, -1]]

const3 = tf.constant(np.array(x))

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int64)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[ 0  2]

 [ 1 -1]]

In [7]:

depth = 3

bm_const3 = tf.one_hot(const3, depth,

    on_value=1.0, off_value=0.0, axis=-1)

print(bm_const3)

print(tf.shape(bm_const3))

tfutil.print_operation_value(bm_const3)

Tensor("one_hot_2:0", shape=(2, 2, 3), dtype=float32)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[[ 1.  0.  0.]

  [ 0.  0.  1.]]

 [[ 0.  1.  0.]

  [ 0.  0.  0.]]]


기타 함수 및 클래스


tf.bitcast(input, type, name=None)


텐서를 다른 자료형으로 데이터 복사 없이 비트캐스트(bitcast)합니다.


input 텐서가 주어질 때, 이 함수는 input과 같은 버퍼 데이터를 가진 자료형 type의 텐서를 반환합니다.

만약 입력의 자료형 T가 출력의 자료형 type에 비해 더 큰 경우, 구조(shape)가 [...]에서 [..., sizeof(T)/sizeof(type)]으로 변형됩니다.

만약 T가 type에 비해 더 작은 경우, 가장 오른쪽의 차원이 sizeof(type)/sizeof(T)와 같아야 합니다. 구조는 [..., sizeof(type)/sizeof(T)] to [...]으로 변형됩니다.

인자:
  • inputTensor. 다음의 자료형이 가능합니다: float32float64int64int32uint8uint16int16int8complex64complex128qint8quint8qint32half.
  • typetf.DType. 다음 중 하나가 가능합니다: tf.float32, tf.float64, tf.int64, tf.int32, tf.uint8, tf.uint16, tf.int16, tf.int8, tf.complex64, tf.complex128, tf.qint8, tf.quint8, tf.qint32, tf.half.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

type 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.bitcast 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = 37.0

const1 = tf.constant(x) 

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(), dtype=float32)

Tensor("Shape:0", shape=(0,), dtype=int32)

37.0

In [3]:

bc_const1 = tf.bitcast(const1, tf.int32)

print(bc_const1)

print(tf.shape(bc_const1))

tfutil.print_operation_value(bc_const1)

Tensor("Bitcast:0", shape=(), dtype=int32)

Tensor("Shape_1:0", shape=(0,), dtype=int32)

1108606976

In [4]:

x = -1

invert_bits = tf.constant(x) - bc_const1

print(invert_bits)

print(tf.shape(invert_bits))

tfutil.print_operation_value(invert_bits)

Tensor("sub:0", shape=(), dtype=int32)

Tensor("Shape_2:0", shape=(0,), dtype=int32)

-1108606977

In [5]:

bc_to_float = tf.bitcast(invert_bits, tf.float32)

print(bc_to_float)

print(tf.shape(bc_to_float))

tfutil.print_operation_value(bc_to_float)

Tensor("Bitcast_1:0", shape=(), dtype=float32)

Tensor("Shape_3:0", shape=(0,), dtype=int32)

-0.115234


tf.shape_n(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input[i]들의 구조를 나타내는 N개의 1-D 정수 텐서를 반환합니다.

인자:
  • input: 같은 자료형의 1개 이상의 Tensor의 리스트.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input의 텐서와 같은 개수의 int32형 Tensor의 리스트.


출처: 텐서 변환


Tensorflow tf.shape_n 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [1]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1]

In [3]:

sn_const1 = tf.shape_n([const1])

print(sn_const1)

tfutil.print_operation_value(sn_const1)

[<tf.Tensor 'ShapeN:0' shape=(1,) dtype=int32>]

[array([1], dtype=int32)]

In [4]:

x = [1, 2]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2]

In [5]:

sn_const2 = tf.shape_n([const2])

print(sn_const2)

tfutil.print_operation_value(sn_const2)

[<tf.Tensor 'ShapeN_1:0' shape=(1,) dtype=int32>]

[array([2], dtype=int32)]

In [6]:

x = [[1, 2], [3, 4]]

const3 = tf.constant(np.array(x))

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]]

In [7]:

sn_const3 = tf.shape_n([const3])

print(sn_const3)

tfutil.print_operation_value(sn_const3)

[<tf.Tensor 'ShapeN_2:0' shape=(2,) dtype=int32>]

[array([2, 2], dtype=int32)]

In [8]:

x = [[1, 2], [3, 4], [5, 6]]

const4 = tf.constant(np.array(x))

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int64)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]

 [5 6]]

In [9]:

sn_const4 = tf.shape_n([const4])

print(sn_const4)

tfutil.print_operation_value(sn_const4)

[<tf.Tensor 'ShapeN_3:0' shape=(2,) dtype=int32>]

[array([3, 2], dtype=int32)]

In [10]:

x = [[[1], [2]], [[3], [4]]]

const5 = tf.constant(np.array(x))

print(const5)

print(tf.shape(const5))

tfutil.print_constant(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int64)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]]

In [11]:

sn_const5 = tf.shape_n([const5])

print(sn_const5)

tfutil.print_operation_value(sn_const5)

[<tf.Tensor 'ShapeN_4:0' shape=(3,) dtype=int32>]

[array([2, 2, 1], dtype=int32)]

In [12]:

x = [[[1], [2]], [[3], [4]], [[5], [6]]]

const6 = tf.constant(np.array(x))

print(const6)

print(tf.shape(const6))

tfutil.print_constant(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int64)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [13]:

sn_const6 = tf.shape_n([const6])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_5:0' shape=(3,) dtype=int32>]

[array([3, 2, 1], dtype=int32)]

In [14]:

sn_const6 = tf.shape_n([[const6]])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_6:0' shape=(4,) dtype=int32>]

[array([1, 3, 2, 1], dtype=int32)]


tf.unique_with_counts(x, name=None)


1-D 텐서에서 서로 다른 원소를 찾습니다.


이 함수는 텐서 x의 모든 서로 다른 원소를 x에서 나타나는 순서대로 나열한 텐서 y를 반환합니다. 이 함수는 크기가 x와 같고, x의 각 원소에 대해 y에서의 인덱서를 원소를 가지는 텐서 idx도 반환합니다. y의 각 원소가 x에서 몇 번 나타나는지에 대한 텐서 count도 반환합니다. 즉,

y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]

입니다.


예시:

# tensor 'x'는 [1, 1, 2, 4, 4, 4, 7, 8, 8]

y, idx, count = unique_with_counts(x)

y ==> [1, 2, 4, 7, 8]

idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]

count ==> [2, 1, 3, 1, 2]

인자:
  • x: 1-D Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

Tensor의 튜플 (y, idx, count).

  • yx와 자료형이 같은 1-D Tensor.
  • idxint32형 1-D Tensor.
  • countint32형 1-D Tensor.

출처: 텐서 변환


Tensorflow tf.unique_with_counts 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [1, 1, 2, 4, 4, 4, 7, 8, 8]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(9,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 1 2 4 4 4 7 8 8]

In [3]:

y, idx, count = tf.unique_with_counts(const1)

print(y)

print(tf.shape(y))

tfutil.print_constant(y)

Tensor("UniqueWithCounts:0", shape=(?,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2 4 7 8]

In [4]:

print(idx)

print(tf.shape(idx))

tfutil.print_constant(idx)

Tensor("UniqueWithCounts:1", shape=(9,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[0 0 1 2 2 2 3 4 4]

In [5]:

print(count)

print(tf.shape(count))

tfutil.print_constant(count)

Tensor("UniqueWithCounts:2", shape=(?,), dtype=int32)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[2 1 3 1 2]



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Convert to Tensor - Shape and Shaping

(텐서플로우 텐서 변환 - 구조 및 구조 변형)



구조(Shape) 및 구조 변형(Shaping)

TensorFlow는 텐서의 구조(shape)를 확인하거나 구조를 변형하는 데 사용할 수 있는 몇 가지 함수를 제공합니다.


tf.shape(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input 텐서의 구조(shape)를 1-D 정수형 텐서로 반환합니다.


예시:

# 't'는 [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]

shape(t) ==> [2, 2, 3]

인자:
  • inputTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

int32형 Tensor.


출처: 텐서 변환


Tensorflow tf.tf.shape 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: tfutil.print_operation_value(tf.shape(const1))

[]

In [7]: const2 = tf.constant([12])

In [8]: tfutil.print_constant(const2)

[1 2]

In [9]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [10]: tfutil.print_operation_value(tf.shape(const2))

[2]

In [11]: const3 = tf.constant([[12], [34]])

In [12]: tfutil.print_constant(const3)

[[1 2]

 [3 4]]

In [13]: print(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int32)

In [14]: tfutil.print_operation_value(tf.shape(const3))

[2 2]

In [15]: const3 = tf.constant([[12], [34], [56]])

In [16]: tfutil.print_constant(const3)

[[1 2]

 [3 4]

 [5 6]]

In [17]: print(const3)

Tensor("Const_3:0", shape=(3, 2), dtype=int32)

In [18]: tfutil.print_operation_value(tf.shape(const3))

[3 2]

In [19]: const5 = tf.constant([[[1], [2]], [[3], [4]]])

In [20]: tfutil.print_constant(const5)

[[[1]

  [2]]

 [[3]

  [4]]]

In [21]: print(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int32)

In [22]: tfutil.print_operation_value(tf.shape(const5))

[2 2 1]

In [23]: const6 = tf.constant([[[1], [2]], [[3], [4]], [[5], [6]]])

In [24]: tfutil.print_constant(const6)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [25]: print(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int32)

In [26]: tfutil.print_operation_value(tf.shape(const6))

[3 2 1]


tf.shape_n(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input[i]들의 구조를 나타내는 N개의 1-D 정수 텐서를 반환합니다.

인자:
  • input: 같은 자료형의 1개 이상의 Tensor의 리스트.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input의 텐서와 같은 개수의 int32형 Tensor의 리스트.


출처: 텐서 변환


Tensorflow tf.shape_n 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

= [1]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1]

In [3]:

sn_const1 = tf.shape_n([const1])

print(sn_const1)

tfutil.print_operation_value(sn_const1)

[<tf.Tensor 'ShapeN:0' shape=(1,) dtype=int32>]

[array([1], dtype=int32)]

In [4]:

= [12]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2]

In [5]:

sn_const2 = tf.shape_n([const2])

print(sn_const2)

tfutil.print_operation_value(sn_const2)

[<tf.Tensor 'ShapeN_1:0' shape=(1,) dtype=int32>]

[array([2], dtype=int32)]

In [6]:

= [[12], [34]]

const3 = tf.constant(np.array(x))

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]]

In [7]:

sn_const3 = tf.shape_n([const3])

print(sn_const3)

tfutil.print_operation_value(sn_const3)

[<tf.Tensor 'ShapeN_2:0' shape=(2,) dtype=int32>]

[array([2, 2], dtype=int32)]

In [8]:

= [[12], [34], [56]]

const4 = tf.constant(np.array(x))

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int64)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]

 [5 6]]

In [9]:

sn_const4 = tf.shape_n([const4])

print(sn_const4)

tfutil.print_operation_value(sn_const4)

[<tf.Tensor 'ShapeN_3:0' shape=(2,) dtype=int32>]

[array([3, 2], dtype=int32)]

In [10]:

= [[[1], [2]], [[3], [4]]]

const5 = tf.constant(np.array(x))

print(const5)

print(tf.shape(const5))

tfutil.print_constant(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int64)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]]

In [11]:

sn_const5 = tf.shape_n([const5])

print(sn_const5)

tfutil.print_operation_value(sn_const5)

[<tf.Tensor 'ShapeN_4:0' shape=(3,) dtype=int32>]

[array([2, 2, 1], dtype=int32)]

In [12]:

= [[[1], [2]], [[3], [4]], [[5], [6]]]

const6 = tf.constant(np.array(x))

print(const6)

print(tf.shape(const6))

tfutil.print_constant(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int64)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [13]:

sn_const6 = tf.shape_n([const6])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_5:0' shape=(3,) dtype=int32>]

[array([3, 2, 1], dtype=int32)]

In [14]:

sn_const6 = tf.shape_n([[const6]])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_6:0' shape=(4,) dtype=int32>]

[array([1, 3, 2, 1], dtype=int32)]


tf.size(input, name=None)


텐서의 크기(size)를 반환합니다.


이 함수는 input 텐서의 원소의 수를 정수로 반환합니다.


예시:

# 't'는 [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]]

size(t) ==> 12

인자:
  • inputTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

int32형 Tensor.


출처: 텐서 변환


Tensorflow tf.size 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: tfutil.print_operation_value(tf.size(const1))

1

In [7]: const2 = tf.constant([12])

In [8]: tfutil.print_constant(const2)

[1 2]

In [9]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [10]: tfutil.print_operation_value(tf.size(const2))

2

In [11]: const3 = tf.constant([[12], [34]])

In [12]: tfutil.print_constant(const3)

[[1 2]

 [3 4]]

In [13]: print(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int32)

In [14]: tfutil.print_operation_value(tf.size(const3))

4

In [15]: const4 = tf.constant([[12], [34], [56]])

In [16]: tfutil.print_constant(const4)

[[1 2]

 [3 4]

 [5 6]]

In [17]: print(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int32)

In [18]: tfutil.print_operation_value(tf.size(const4))

6

In [19]: const5 = tf.constant([[[1], [2]], [[3], [4]]])

In [20]: tfutil.print_constant(const5)

[[[1]

  [2]]

 [[3]

  [4]]]

In [21]: print(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int32)

In [22]: tfutil.print_operation_value(tf.size(const5))

4

In [23]: const6 = tf.constant([[[1], [2]], [[3], [4]], [[5], [6]]])

In [24]: tfutil.print_constant(const6)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [25]: print(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int32)

In [26]: tfutil.print_operation_value(tf.size(const6))

6


tf.rank(input, name=None) 


텐서의 랭크(rank)를 반환합니다.


이 함수는  input  텐서의 랭크를 정수로 반환합니다.


예시:

# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]

# shape of tensor 't' is [2, 2, 3]

rank(t) ==> 3


참고: 텐서의 랭크는 행렬의 랭크와는 다른 개념입니다. 텐서의 랭크는 텐서의 각 원소를 선택하기 위해 필요한 인덱스의 수입니다. 랭크는 order, degree, ndims 등으로 부르기도 합니다.


인자:

• input :  Tensor  또는  SparseTensor .

• name : 오퍼레이션의 명칭. (선택사항)


반환값:


 int32 형  Tensor .


출처: 텐서 변환


Tensorflow tf.rank 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: tfutil.print_operation_value(tf.rank(const1))

0

In [7]: const2 = tf.constant([12])

In [8]: tfutil.print_constant(const2)

[1 2]

In [9]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [10]: tfutil.print_operation_value(tf.rank(const2))

1

In [11]: const3 = tf.constant([[12], [34]])

In [12]: tfutil.print_constant(const3)

[[1 2]

 [3 4]]

In [13]: print(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int32)

In [14]: tfutil.print_operation_value(tf.rank(const3))

2

In [15]: const4 = tf.constant([[12], [34], [56]])

In [16]: tfutil.print_constant(const4)

[[1 2]

 [3 4]

 [5 6]]

In [17]: print(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int32)

In [18]: tfutil.print_operation_value(tf.rank(const4))

2

In [19]: const5 = tf.constant([[[1], [2]], [[3], [4]]])

In [20]: tfutil.print_constant(const5)

[[[1]

  [2]]

 [[3]

  [4]]]

In [21]: print(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int32)

In [22]: tfutil.print_operation_value(tf.rank(const5))

3

In [23]: const6 = tf.constant([[[1], [2]], [[3], [4]], [[5], [6]]])

In [24]: tfutil.print_constant(const6)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [25]: print(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int32)

In [26]: tfutil.print_operation_value(tf.rank(const6))

3


tf.reshape(tensor, shape, name=None)


텐서의 구조를 변형합니다.


tensor가 주어졌을 때, 이 함수는 해당 텐서와 같은 원소들을 가지며 구조가 shape인 텐서를 반환합니다.


만약 shape의 한 원소가 -1이라면, 전체 크기가 일정하게 유지되도록 해당 차원의 길이가 자동으로 계산됩니다. 특별히, shape가 [-1]이라면, 텐서는 1-D로 펴지게 됩니다. shape에서 최대 한 개의 원소만 -1이 될 수 있습니다.


만약 shape가 1-D이거나 그 이상이라면, 오퍼레이션은 tensor의 원소로 shape의 구조가 채워진 텐서를 반환합니다. 이 경우, shape에 의해 지정된 원소의 전체 수는 tensor의 원소의 전체 수와 동일해야 합니다.


예시:

# tensor 't'는 [1, 2, 3, 4, 5, 6, 7, 8, 9]

# tensor 't'의 구조(shape)는 [9]

reshape(t, [3, 3]) ==> [[1, 2, 3],

                        [4, 5, 6],

                        [7, 8, 9]]


# tensor 't'는 [[[1, 1], [2, 2]],

#               [[3, 3], [4, 4]]]

# tensor 't'의 구조(shape)는 [2, 2, 2]

reshape(t, [2, 4]) ==> [[1, 1, 2, 2],

                        [3, 3, 4, 4]]


# tensor 't'는 [[[1, 1, 1],

#                [2, 2, 2]],

#               [[3, 3, 3],

#                [4, 4, 4]],

#               [[5, 5, 5],

#                [6, 6, 6]]]

# tensor 't'의 구조(shape)는 [3, 2, 3]

# shape를 '[-1]'로 하여 't'를 1-D로 펴기

reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]


# 구조를 암시(infer)하기 위한 -1의 사용


# -1은 9를 의미:

reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],

                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]

# -1은 2를 의미:

reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],

                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]

# -1은 3을 의미:

reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],

                              [2, 2, 2],

                              [3, 3, 3]],

                             [[4, 4, 4],

                              [5, 5, 5],

                              [6, 6, 6]]]


# tensor 't'는 [7]

# shape를 `[]`로 하면 스칼라(scalar)로 구조 변환

reshape(t, []) ==> 7

인자:
  • tensorTensor.
  • shapeint32형 Tensor. 출력 텐서의 구조(shape) 지정.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

tensor와 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.reshape 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant([123456789])

In [4]: print(const1)

Tensor("Const:0", shape=(9,), dtype=int32)

In [5]: tfutil.print_constant(const1)

[1 2 3 4 5 6 7 8 9]

In [6]: rs_const1 = tf.reshape(const1, [33])

In [7]: print(rs_const1)

Tensor("Reshape:0", shape=(3, 3), dtype=int32)

In [8]: tfutil.print_operation_value(rs_const1)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [9]: const2 = tf.constant([[[11], [22]], [[33], [44]]])

In [10]: print(const2)

Tensor("Const_1:0", shape=(2, 2, 2), dtype=int32)

In [11]: tfutil.print_constant(const2)

[[[1 1]

  [2 2]]

 [[3 3]

  [4 4]]]

In [12]: rs_const2 = tf.reshape(const2, [24])

In [13]: print(rs_const2)

Tensor("Reshape_1:0", shape=(2, 4), dtype=int32)

In [14]: tfutil.print_operation_value(rs_const2)

[[1 1 2 2]

 [3 3 4 4]]

In [15]: const3 = tf.constant([[[111], [222]], [[333], [444]], [[555], [666]]])

In [16]: print(const3)

Tensor("Const_2:0", shape=(3, 2, 3), dtype=int32)

In [17]: tfutil.print_constant(const3)

[[[1 1 1]

  [2 2 2]]

 [[3 3 3]

  [4 4 4]]

 [[5 5 5]

  [6 6 6]]]

In [18]: rs_const3 = tf.reshape(const3, [-1])

In [19]: print(rs_const3)

Tensor("Reshape_2:0", shape=(18,), dtype=int32)

In [20]: tfutil.print_operation_value(rs_const3)

[1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6]

In [21]: const4 = tf.constant([111222333444555666])

In [22]: print(const4)

Tensor("Const_3:0", shape=(18,), dtype=int32)

In [23]: tfutil.print_constant(const4)

[1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6]

In [24]: rs_const4 = tf.reshape(const4, [2-1])

In [25]: print(rs_const4)

Tensor("Reshape_3:0", shape=(2, 9), dtype=int32)

In [26]: tfutil.print_operation_value(rs_const4)

[[1 1 1 2 2 2 3 3 3]

 [4 4 4 5 5 5 6 6 6]]

In [27]: const5 = tf.constant([[111222333], [444555666]])

In [28]: print(const5)

Tensor("Const_4:0", shape=(2, 9), dtype=int32)

In [29]: tfutil.print_constant(const5)

[[1 1 1 2 2 2 3 3 3]

 [4 4 4 5 5 5 6 6 6]]

In [30]: rs_const5 = tf.reshape(const5, [2-13])

In [31]: print(rs_const5)

Tensor("Reshape_4:0", shape=(2, 3, 3), dtype=int32)

In [32]: tfutil.print_operation_value(rs_const5)

[[[1 1 1]

  [2 2 2]

  [3 3 3]]

 [[4 4 4]

  [5 5 5]

  [6 6 6]]]

In [33]: const6 = tf.constant([7])

In [34]: print(const6)

Tensor("Const_5:0", shape=(1,), dtype=int32)

In [35]: tfutil.print_constant(const6)

[7]

In [36]: rs_const6 = tf.reshape(const6, [])

In [37]: print(rs_const6)

Tensor("Reshape_5:0", shape=(), dtype=int32)

In [38]: tfutil.print_operation_value(rs_const6)

7


tf.squeeze(input, squeeze_dims=None, name=None)


텐서에서 크기 1인 차원을 제거합니다.


input 텐서가 주어졌을 때, 이 함수는 그와 같은 자료형의 크기 1인 차원이 모두 제거된 텐서를 반환합니다. 만약 모든 크기 1인 차원을 제거하고 싶은 것이 아니라면, 제거하고 싶은 특정한 크기 1인 차원들을 squeeze_dims으로 지정할 수 있습니다.


예시:

# 't'는 구조(shape) [1, 2, 1, 3, 1, 1]의 텐서

shape(squeeze(t)) ==> [2, 3]


제거할 크기 1인 차원들을 squeeze_dims으로 지정하기:

# 't'는 구조(shape) [1, 2, 1, 3, 1, 1]의 텐서
shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]
인자:
  • inputTensor.
  • squeeze_dimsint의 리스트. 기본값은 []. 지정된 경우, 리스트 안의 차원만 제거합니다. 크기가 1이 아닌 차원을 제거하는 것은 오류입니다. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensorinput과 같은 원소를 포함하지만, 하나 이상의 크기 1인 차원이 제거되어 있습니다.


출처: 텐서 변환


Tensorflow tf.squeeze 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: # [1, 2, 1, 3, 1, 1]

In [4]: const1 = tf.constant([[ [[ [[1]], [[2]], [[3]] ]], [[ [[4]], [[5]], [[6]] ]] ]])

In [5]: print(const1)

Tensor("Const:0", shape=(1, 2, 1, 3, 1, 1), dtype=int32)

In [6]: print(tf.shape(const1))

Tensor("Shape:0", shape=(6,), dtype=int32)

In [7]: tfutil.print_constant(const1)

[[[[[[1]]

    [[2]]

    [[3]]]]

  [[[[4]]

    [[5]]

    [[6]]]]]]

In [8]: sq_const1 = tf.squeeze(const1)

In [9]: print(sq_const1)

Tensor("Squeeze:0", shape=(2, 3), dtype=int32)

In [10]: print(tf.shape(sq_const1))

Tensor("Shape_1:0", shape=(2,), dtype=int32)

In [11]: tfutil.print_operation_value(sq_const1)

[[1 2 3]

 [4 5 6]]

In [12]: # [1, 2, 1, 3, 1, 1]

In [13]: const2 = tf.constant([[ [[ [[1]], [[2]], [[3]] ]], [[ [[4]], [[5]], [[6]] ]] ]])

In [14]: print(const2)

Tensor("Const_1:0", shape=(1, 2, 1, 3, 1, 1), dtype=int32)

In [15]: print(tf.shape(const2))

Tensor("Shape_2:0", shape=(6,), dtype=int32)

In [16]: tfutil.print_constant(const2)

[[[[[[1]]

    [[2]]

    [[3]]]]

  [[[[4]]

    [[5]]

    [[6]]]]]]

In [17]: sq_const2 = tf.squeeze(const2, [0])

In [18]: print(sq_const2)

Tensor("Squeeze_1:0", shape=(2, 1, 3, 1, 1), dtype=int32)

In [19]: print(tf.shape(sq_const2))

Tensor("Shape_3:0", shape=(5,), dtype=int32)

In [20]: tfutil.print_operation_value(sq_const2)

[[[[[1]]

   [[2]]

   [[3]]]]

 [[[[4]]

   [[5]]

   [[6]]]]]

In [21]: sq_const2 = tf.squeeze(const2, [2])

In [22]: print(sq_const2)

Tensor("Squeeze_2:0", shape=(1, 2, 3, 1, 1), dtype=int32)

In [23]: print(tf.shape(sq_const2))

Tensor("Shape_4:0", shape=(5,), dtype=int32)

In [24]: tfutil.print_operation_value(sq_const2)

[[[[[1]]

   [[2]]

   [[3]]]

  [[[4]]

   [[5]]

   [[6]]]]]

In [25]: sq_const2 = tf.squeeze(const2, [02])

In [26]: print(sq_const2)

Tensor("Squeeze_3:0", shape=(2, 3, 1, 1), dtype=int32)

In [27]: print(tf.shape(sq_const2))

Tensor("Shape_5:0", shape=(4,), dtype=int32)

In [28]: tfutil.print_operation_value(sq_const2)

[[[[1]]

  [[2]]

  [[3]]]

 [[[4]]

  [[5]]

  [[6]]]]

In [29]: sq_const2 = tf.squeeze(const2, [24])

In [30]: print(sq_const2)

Tensor("Squeeze_4:0", shape=(1, 2, 3, 1), dtype=int32)

In [31]: print(tf.shape(sq_const2))

Tensor("Shape_6:0", shape=(4,), dtype=int32)

In [32]: tfutil.print_operation_value(sq_const2)

[[[[1]

   [2]

   [3]]

  [[4]

   [5]

   [6]]]]

In [33]: sq_const2 = tf.squeeze(const2, [024])

In [34]: print(sq_const2)

Tensor("Squeeze_5:0", shape=(2, 3, 1), dtype=int32)

In [35]: print(tf.shape(sq_const2))

Tensor("Shape_7:0", shape=(3,), dtype=int32)

In [36]: tfutil.print_operation_value(sq_const2)

[[[1]

  [2]

  [3]]

 [[4]

  [5]

  [6]]]

In [37]: sq_const2 = tf.squeeze(const2, [0245])

In [38]: print(sq_const2)

Tensor("Squeeze_6:0", shape=(2, 3), dtype=int32)

In [39]: print(tf.shape(sq_const2))

Tensor("Shape_8:0", shape=(2,), dtype=int32)

In [40]: tfutil.print_operation_value(sq_const2)

[[1 2 3]

 [4 5 6]]


tf.expand_dims(input, dim, name=None)


크기 1인 차원을 텐서의 구조(shape)에 삽입합니다.


input 텐서가 주어졌을 때, 이 함수는 크기가 1인 차원을 input의 구조에서 차원 인덱스 dim에 삽입합니다. 차원 인덱스 dim은 0부터 시작합니다. 만약 dim에 음수가 지정된다면, 끝에서부터 역으로 계산됩니다.


이 함수는 단일 원소에 배치 차원(batch dimension)을 추가할 때 유용합니다. 예로, 만약 구조 [height, width, channels]의 단일 이미지가 있는 경우, 이것에 expand_dims(image, 0)을 적용해 구조 [1, height, width, channels]인 하나의 이미지로 구성된 배치(batch)를 구성할 수 있습니다.


다른 예시들:

# 't'는 구조(shape) [2]의 텐서
shape(expand_dims(t, 0)) ==> [1, 2]
shape(expand_dims(t, 1)) ==> [2, 1]
shape(expand_dims(t, -1)) ==> [2, 1]

# 't2'는 구조(shape) [2, 3, 5]의 텐서
shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]


이 함수는 다음의 조건이 만족되어야 합니다:


-1-input.dims() <= dim <= input.dims()


이 함수는 크기 1인 차원을 제거하는 함수인 squeeze()와 연관되어 있습니다.

인자:
  • inputTensor.
  • dimint32형 Tensor. 0-D (스칼라). input의 구조에서 어떤 차원 인덱스에 삽입할 것인지 지정합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensorinput과 같은 원소를 포함하지만, 하나 이상의 크기 1인 차원이 추가되어 있습니다.


출처: 텐서 변환


Tensorflow tf.expand_dims 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant([123])

In [4]: print(const1)

Tensor("Const:0", shape=(3,), dtype=int32)

In [5]: print(tf.shape(const1))

Tensor("Shape:0", shape=(1,), dtype=int32)

In [6]: tfutil.print_constant(const1)

[1 2 3]

In [7]: ed_const1 = tf.expand_dims(const1, 0)

In [8]: print(ed_const1)

Tensor("ExpandDims:0", shape=(1, 3), dtype=int32)

In [9]: tfutil.print_operation_value(ed_const1)

[[1 2 3]]

In [10]: print(tf.shape(ed_const1))

Tensor("Shape_1:0", shape=(2,), dtype=int32)

In [11]: ed_const1 = tf.expand_dims(const1, 1)

In [12]: print(ed_const1)

Tensor("ExpandDims_1:0", shape=(3, 1), dtype=int32)

In [13]: tfutil.print_operation_value(ed_const1)

[[1]

 [2]

 [3]]

In [14]: print(tf.shape(ed_const1))

Tensor("Shape_2:0", shape=(2,), dtype=int32)

In [15]: ed_const1 = tf.expand_dims(const1, 1)

In [16]: print(ed_const1)

Tensor("ExpandDims_2:0", shape=(3, 1), dtype=int32)

In [17]: tfutil.print_operation_value(ed_const1)

[[1]

 [2]

 [3]]

In [18]: print(tf.shape(ed_const1))

Tensor("Shape_3:0", shape=(2,), dtype=int32)

In [19]: ed_const1 = tf.expand_dims(const1, -1)

In [20]: print(ed_const1)

Tensor("ExpandDims_3:0", shape=(3, 1), dtype=int32)

In [21]: tfutil.print_operation_value(ed_const1)

[[1]

 [2]

 [3]]

In [22]: print(tf.shape(ed_const1))

Tensor("Shape_4:0", shape=(2,), dtype=int32)

In [23]: const2 = tf.constant([[[12345], [678910], [1112131415]], [[1617181920], [2122232425], [2627282930]]])

In [24]: print(const2)

Tensor("Const_1:0", shape=(2, 3, 5), dtype=int32)

In [25]: print(tf.shape(const2))

Tensor("Shape_5:0", shape=(3,), dtype=int32)

In [26]: tfutil.print_constant(const2)

[[[ 1  2  3  4  5]

  [ 6  7  8  9 10]

  [11 12 13 14 15]]

 [[16 17 18 19 20]

  [21 22 23 24 25]

  [26 27 28 29 30]]]

In [27]: ed_const2 = tf.expand_dims(const2, 0)

In [28]: print(ed_const2)

Tensor("ExpandDims_4:0", shape=(1, 2, 3, 5), dtype=int32)

In [29]: tfutil.print_operation_value(ed_const2)

[[[[ 1  2  3  4  5]

   [ 6  7  8  9 10]

   [11 12 13 14 15]]

  [[16 17 18 19 20]

   [21 22 23 24 25]

   [26 27 28 29 30]]]]

In [30]: print(tf.shape(ed_const2))

Tensor("Shape_6:0", shape=(4,), dtype=int32)

In [31]: ed_const2 = tf.expand_dims(const2, 1)

In [32]: print(ed_const2)

Tensor("ExpandDims_5:0", shape=(2, 1, 3, 5), dtype=int32)

In [33]: tfutil.print_operation_value(ed_const2)

[[[[ 1  2  3  4  5]

   [ 6  7  8  9 10]

   [11 12 13 14 15]]]

 [[[16 17 18 19 20]

   [21 22 23 24 25]

   [26 27 28 29 30]]]]

In [34]: print(tf.shape(ed_const2))

Tensor("Shape_7:0", shape=(4,), dtype=int32)

In [35]: ed_const2 = tf.expand_dims(const2, 2)

In [36]: print(ed_const2)

Tensor("ExpandDims_6:0", shape=(2, 3, 1, 5), dtype=int32)

In [37]: tfutil.print_operation_value(ed_const2)

[[[[ 1  2  3  4  5]]

  [[ 6  7  8  9 10]]

  [[11 12 13 14 15]]]

 [[[16 17 18 19 20]]

  [[21 22 23 24 25]]

  [[26 27 28 29 30]]]]

In [38]: print(tf.shape(ed_const2))

Tensor("Shape_8:0", shape=(4,), dtype=int32)

In [39]: ed_const2 = tf.expand_dims(const2, 3)

In [40]: print(ed_const2)

Tensor("ExpandDims_7:0", shape=(2, 3, 5, 1), dtype=int32)

In [41]: tfutil.print_operation_value(ed_const2)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]

   [ 5]]

  [[ 6]

   [ 7]

   [ 8]

   [ 9]

   [10]]

  [[11]

   [12]

   [13]

   [14]

   [15]]]

 [[[16]

   [17]

   [18]

   [19]

   [20]]

  [[21]

   [22]

   [23]

   [24]

   [25]]

  [[26]

   [27]

   [28]

   [29]

   [30]]]]

In [42]: print(tf.shape(ed_const2))

Tensor("Shape_9:0", shape=(4,), dtype=int32)

In [43]: ed_const2 = tf.expand_dims(const2, -1)

In [44]: print(ed_const2)

Tensor("ExpandDims_8:0", shape=(2, 3, 5, 1), dtype=int32)

In [45]: tfutil.print_operation_value(ed_const2)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]

   [ 5]]

  [[ 6]

   [ 7]

   [ 8]

   [ 9]

   [10]]

  [[11]

   [12]

   [13]

   [14]

   [15]]]

 [[[16]

   [17]

   [18]

   [19]

   [20]]

  [[21]

   [22]

   [23]

   [24]

   [25]]

  [[26]

   [27]

   [28]

   [29]

   [30]]]]

In [46]: print(tf.shape(ed_const2))

Tensor("Shape_10:0", shape=(4,), dtype=int32)


이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Convert to Tensor - Casting

(텐서플로우 텐서 변환 - 형변환)

참고: Tensor를 인자로 받는 함수들은, tf.convert_to_tensor의 인자가 될 수 있는 것들 또한 인자로 받을 수 있습니다.


형변환 (Casting)

TensorFlow는 그래프에 사용되는 텐서 자료형들을 형변환(cast)할 수 있는 몇 가지 함수를 제공합니다.


tf.string_to_number(string_tensor, out_type=None, name=None)


입력 텐서의 각 문자열(string)을 지정된 자료형의 값으로 변환합니다.


(참고로, int32 오버플로우는 에러를 내며, float 오버플로우는 반올림한 결과를 냅니다.)


인자:
  • string_tensor: stringTensor.
  • out_type: tf.DType 오브젝트. tf.float32 또는 tf.int32이어야 하며, 기본값은 tf.float32입니다. 이 자료형으로 string_tensor의 문자열이 변환됩니다. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

out_type형의 Tensor. 출력 텐서는 입력 텐서 string_tensor와 같은 구조(shape)를 가집니다.


출처: 텐서 변환


Tensorflow tf.string_to_number 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: var = tf.Variable("500", dtype=tf.string)
In [4]: tfutil.print_variable(var)
500
In [5]: print(var)
<tf.Variable 'Variable:0' shape=() dtype=string_ref>
In [6]: num1 = tf.string_to_number(var, out_type=tf.int32)
In [7]: tfutil.print_operation_value(num1)
500
In [8]: print(num1)
Tensor("StringToNumber:0", shape=(), dtype=int32)

tf.to_double(x, name='ToDouble')


텐서를 float64형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 float64형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xfloat64형으로 변환될 수 없는 경우.


출처: 텐서 변환


Tensorflow tf.to_double 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: double1 = tf.to_double(const1)

In [7]: tfutil.print_operation_value(double1)

1.0

In [8]: print(double1)

Tensor("ToDouble:0", shape=(), dtype=float64)

In [9]: const2 = tf.constant([2, 3])

In [10]:tfutil.print_constant(const2)

[2 3]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [12]: double2 = tf.to_double(const2)

In [13]: tfutil.print_operation_value(double2)

[ 2.  3.]

In [14]: print(double2)

Tensor("ToDouble_1:0", shape=(2,), dtype=float64)


tf.to_float(x, name='ToFloat')


텐서를 float32형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 float32형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xfloat32형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_float 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: float1 = tf.to_float(const1)

In [7]: tfutil.print_operation_value(float1)

1.0

In [8]: print(float1)

Tensor("ToFloat:0", shape=(), dtype=float32)

In [9]: const2 = tf.constant([23])

In [10]: tfutil.print_constant(const2)

[2 3]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [12]: float2 = tf.to_float(const2)

In [13]: tfutil.print_operation_value(float2)

[ 2.  3.]

In [14]: print(float2)

Tensor("ToFloat_1:0", shape=(2,), dtype=float32)


tf.to_bfloat16(x, name='ToBFloat16')


텐서를 bfloat16형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 bfloat16형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xbfloat16형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_bfloat16 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1, dtype=tf.float32)

In [4]: tfutil.print_constant(const1)

1.0

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=float32)

In [6]: bfloat1 = tf.to_bfloat16(const1)

In [7]: tfutil.print_operation_value(bfloat1)

16256

In [8]: print(bfloat1)

Tensor("ToBFloat16:0", shape=(), dtype=bfloat16)

In [9]: const2 = tf.constant([23], dtype=tf.float32)

In [10]: tfutil.print_constant(const2)

[ 2.  3.]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=float32)

In [12]: bfloat2 = tf.to_bfloat16(const2)

In [13]: tfutil.print_operation_value(bfloat2)

[16384 16448]

In [14]: print(bfloat2)

Tensor("ToBFloat16_1:0", shape=(2,), dtype=bfloat16)


tf.to_int32(x, name='ToInt32')


텐서를 int32형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 int32형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xint32형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_int32 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1, dtype=tf.float32)

In [4]: tfutil.print_constant(const1)

1.0

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=float32)

In [6]: int32_1 = tf.to_int32(const1)

In [7]: tfutil.print_operation_value(int32_1)

1

In [8]: print(int32_1)

Tensor("ToInt32:0", shape=(), dtype=int32)

In [9]: const2 = tf.constant([2, 3], dtype=tf.float32)

In [10]: tfutil.print_constant(const2)

[ 2.  3.]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=float32)

In [12]: int32_2 = tf.to_int32(const2)

In [13]: tfutil.print_operation_value(int32_2)

[2 3]

In [14]: print(int32_2)

Tensor("ToInt32_1:0", shape=(2,), dtype=int32)


tf.to_int64(x, name='ToInt64')


텐서를 int64형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 int64형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xint64형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_int64 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1, dtype=tf.float32)

In [4]: tfutil.print_constant(const1)

1.0

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=float32)

In [6]: int64_1 = tf.to_int64(const1)

In [7]: tfutil.print_operation_value(int64_1)

1

In [8]: print(int64_1)

Tensor("ToInt64:0", shape=(), dtype=int64)

In [9]: const2 = tf.constant([2, 3], dtype=tf.float32)

In [10]: tfutil.print_constant(const2)

[ 2.  3.]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=float32)

In [12]: int64_2 = tf.to_int64(const2)

In [13]: tfutil.print_operation_value(int64_2)

[2 3]

In [14]: print(int64_2)

Tensor("ToInt64_1:0", shape=(2,), dtype=int64)


tf.cast(x, dtype, name=None)


텐서를 새로운 자료형으로 변환합니다.


x(Tensor의 경우) 또는 x.values(SparseTensor의 경우)를 dtype형으로 변환합니다.


예시:

# 텐서 `a`는 [1.8, 2.2], 자료형은 tf.float

tf.cast(a, tf.int32) ==> [1, 2]  # dtype=tf.int32

인자:
  • x: Tensor 또는 SparseTensor.
  • dtype: 변환될 자료형.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 int64형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xdtype형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.cast 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(127, dtype=tf.int32)

In [4]: tfutil.print_constant(const1)

127

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: f32 = tf.cast(const1, tf.float32)

In [7]: tfutil.print_operation_value(f32)

127.0

In [8]: print(f32)

Tensor("Cast:0", shape=(), dtype=float32)

In [9]: f64 = tf.cast(const1, tf.float64)

In [10]: tfutil.print_operation_value(f64)

127.0

In [11]: print(f64)

Tensor("Cast_1:0", shape=(), dtype=float64)

In [12]: i8 = tf.cast(const1, tf.int8)

In [13]: tfutil.print_operation_value(i8)

127

In [14]: print(i8)

Tensor("Cast_2:0", shape=(), dtype=int8)

In [15]: i16 = tf.cast(const1, tf.int16)

In [16]: tfutil.print_operation_value(i16)

127

In [17]: print(i16)

Tensor("Cast_3:0", shape=(), dtype=int16)

In [18]: i64 = tf.cast(const1, tf.int64)

In [19]: tfutil.print_operation_value(i64)

127

In [20]: print(i64)

Tensor("Cast_4:0", shape=(), dtype=int64)

In [21]: u8 = tf.cast(const1, tf.uint8)

In [22]: tfutil.print_operation_value(u8)

127

In [23]: print(u8)

Tensor("Cast_5:0", shape=(), dtype=uint8)

In [24]: const2 = tf.constant([127, 255])

In [25]: tfutil.print_constant(const2)

[127 255]

In [26]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [27]: f32 = tf.cast(const2, tf.float32)

In [28]: tfutil.print_operation_value(f32)

[ 127.  255.]

In [29]: print(f32)

Tensor("Cast_6:0", shape=(2,), dtype=float32)

In [30]: f64 = tf.cast(const2, tf.float64)

In [31]: tfutil.print_operation_value(f64)

[ 127.  255.]

In [32]: print(f64)

Tensor("Cast_7:0", shape=(2,), dtype=float64)

In [33]: i8 = tf.cast(const2, tf.int8)

In [34]: tfutil.print_operation_value(i8)

[127  -1]

In [35]: print(i8)

Tensor("Cast_8:0", shape=(2,), dtype=int8)

In [36]: i16 = tf.cast(const2, tf.int16)

In [37]: tfutil.print_operation_value(i16)

[127 255]

In [38]: print(i16)

Tensor("Cast_9:0", shape=(2,), dtype=int16)

In [39]: i64 = tf.cast(const2, tf.int64)

In [40]: tfutil.print_operation_value(i64)

[127 255]

In [41]: print(i64)

Tensor("Cast_10:0", shape=(2,), dtype=int64)

In [42]: u8 = tf.cast(const2, tf.uint8)

In [43]: tfutil.print_operation_value(u8)

[127 255]

In [44]: print(u8)

Tensor("Cast_11:0", shape=(2,), dtype=uint8)


tf.saturate_cast(value, dtype, name=None)


valuedtype 형으로 안전하게 포화 형변환(saturating cast)합니다.


이 함수는 입력을 dtype으로 스케일링(scaling) 없이 변환합니다. 형변환 시 오버플로우나 언더플로우가 발생할 수 있는 값들에 대해, 이 함수는 해당 값들을 허용되는 값 범위로 넣은 뒤 형변환을 진행합니다.

인자:
  • value: Tensor.
  • dtype: DType 오브젝트. 변환될 자료형.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

dtype형으로 안전하게 변환된 value.


출처: 텐서 변환


Tensorflow tf.saturate_cast 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(127, dtype=tf.int32)

In [4]: tfutil.print_constant(const1)

127

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: f32 = tf.saturate_cast(const1, tf.float32)

In [7]: tfutil.print_operation_value(f32)

127.0

In [8]: print(f32)

Tensor("saturate_cast:0", shape=(), dtype=float32)

In [9]: f64 = tf.saturate_cast(const1, tf.float64)

In [10]: tfutil.print_operation_value(f64)

127.0

In [11]: print(f64)

Tensor("saturate_cast_1:0", shape=(), dtype=float64)

In [12]: i8 = tf.saturate_cast(const1, tf.int8)

In [13]: tfutil.print_operation_value(i8)

127

In [14]: print(i8)

Tensor("saturate_cast_2:0", shape=(), dtype=int8)

In [15]: i16 = tf.saturate_cast(const1, tf.int16)

In [16]: tfutil.print_operation_value(i16)

127

In [17]: print(i16)

Tensor("saturate_cast_3:0", shape=(), dtype=int16)

In [18]: i64 = tf.saturate_cast(const1, tf.int64)

In [19]: tfutil.print_operation_value(i64)

127

In [20]: print(i64)

Tensor("saturate_cast_4:0", shape=(), dtype=int64)

In [21]: u8 = tf.saturate_cast(const1, tf.uint8)

In [22]: tfutil.print_operation_value(u8)

127

In [23]: print(u8)

Tensor("saturate_cast_5:0", shape=(), dtype=uint8)

In [24]: const2 = tf.constant([127, 255])

In [25]: tfutil.print_constant(const2)

[127 255]

In [26]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [27]: f32 = tf.saturate_cast(const2, tf.float32)

In [28]: tfutil.print_operation_value(f32)

[ 127.  255.]

In [29]: print(f32)

Tensor("saturate_cast_6:0", shape=(2,), dtype=float32)

In [30]: f64 = tf.saturate_cast(const2, tf.float64)

In [31]: tfutil.print_operation_value(f64)

[ 127.  255.]

In [32]: print(f64)

Tensor("saturate_cast_7:0", shape=(2,), dtype=float64)

In [33]: i8 = tf.saturate_cast(const2, tf.int8)

In [34]: tfutil.print_operation_value(i8)

[127 127]

In [35]: print(i8)

Tensor("saturate_cast_8:0", shape=(2,), dtype=int8)

In [36]: i16 = tf.saturate_cast(const2, tf.int16)

In [37]: tfutil.print_operation_value(i16)

[127 255]

In [38]: print(i16)

Tensor("saturate_cast_9:0", shape=(2,), dtype=int16)

In [39]: i64 = tf.saturate_cast(const2, tf.int64)

In [40]: tfutil.print_operation_value(i64)

[127 255]

In [41]: print(i64)

Tensor("saturate_cast_10:0", shape=(2,), dtype=int64)

In [42]: u8 = tf.saturate_cast(const2, tf.uint8)

In [43]: tfutil.print_operation_value(u8)

[127 255]

In [44]: print(u8)

Tensor("saturate_cast_11:0", shape=(2,), dtype=uint8)


tf.bitcast(input, type, name=None)


텐서를 다른 자료형으로 데이터 복사 없이 비트캐스트(bitcast)합니다.


input 텐서가 주어질 때, 이 함수는 input과 같은 버퍼 데이터를 가진 자료형 type의 텐서를 반환합니다.

만약 입력의 자료형 T가 출력의 자료형 type에 비해 더 큰 경우, 구조(shape)가 [...]에서 [..., sizeof(T)/sizeof(type)]으로 변형됩니다.

만약 T가 type에 비해 더 작은 경우, 가장 오른쪽의 차원이 sizeof(type)/sizeof(T)와 같아야 합니다. 구조는 [..., sizeof(type)/sizeof(T)] to [...]으로 변형됩니다.

인자:
  • inputTensor. 다음의 자료형이 가능합니다: float32float64int64int32uint8uint16int16int8complex64complex128qint8quint8qint32half.
  • typetf.DType. 다음 중 하나가 가능합니다: tf.float32, tf.float64, tf.int64, tf.int32, tf.uint8, tf.uint16, tf.int16, tf.int8, tf.complex64, tf.complex128, tf.qint8, tf.quint8, tf.qint32, tf.half.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

type 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.bitcast 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

= 37.0

const1 = tf.constant(x) 

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(), dtype=float32)

Tensor("Shape:0", shape=(0,), dtype=int32)

37.0

In [3]:

bc_const1 = tf.bitcast(const1, tf.int32)

print(bc_const1)

print(tf.shape(bc_const1))

tfutil.print_operation_value(bc_const1)

Tensor("Bitcast:0", shape=(), dtype=int32)

Tensor("Shape_1:0", shape=(0,), dtype=int32)

1108606976

In [4]:

= -1

invert_bits = tf.constant(x) - bc_const1

print(invert_bits)

print(tf.shape(invert_bits))

tfutil.print_operation_value(invert_bits)

Tensor("sub:0", shape=(), dtype=int32)

Tensor("Shape_2:0", shape=(0,), dtype=int32)

-1108606977

In [5]:

bc_to_float = tf.bitcast(invert_bits, tf.float32)

print(bc_to_float)

print(tf.shape(bc_to_float))

tfutil.print_operation_value(bc_to_float)

Tensor("Bitcast_1:0", shape=(), dtype=float32)

Tensor("Shape_3:0", shape=(0,), dtype=int32)

-0.115234


tf.shape_n(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input[i]들의 구조를 나타내는 N개의 1-D 정수 텐서를 반환합니다.

인자:
  • input: 같은 자료형의 1개 이상의 Tensor의 리스트.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input의 텐서와 같은 개수의 int32형 Tensor의 리스트.


출처: 텐서 변환



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Variables

(텐서플로우 변수)

Note: 함수의 Tensor 인자는 tf.convert_to_tensor에 의한 것도 가능합니다.


class tf.Variable


class tf.Variable

Variables How To에서 자세한 개요를 확인할 수 있습니다.


변수는 graph에서 run()의 호출로 상태를 유지합니다. Variable의 객체를 만들어 graph에 변수를 추가합니다.


Variable() 생성자는 변수의 초기값으로 Tensor의 type과 shape이 필요합니다. 초기값은 변수의 type과 shape를 정의합니다. 생성 후, 변수의 type과 shape은 고정됩니다. 변수의 값은 assign 메소드를 사용해 변경할 수 있습니다.


후에 변수의 shape를 변경하고 싶다면 assign에서 validate_shape=False로 해야합니다.


Tensor의 경우, Variable()로 만들어진 변수는 graph의 ops의 input으로 사용될 수 있습니다. 추가적으로, Tensor 클래스로 오버로드 되는 모든 연산(operators)은 변수로 넘겨집니다. 그래서 변수의 산술연산만으로도 graph에 노드를 추가할 수 있습니다.

import tensorflow as tf

# Create a variable.
w = tf.Variable(<initial-value>, name=<optional-name>)

# Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...)

# The overloaded operators are available too.
z = tf.sigmoid(w + y)

# Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)


graph를 실행할 때, 변수는 그 값을 사용하는 ops를 실행하기 전에 명시적으로 초기화해야 합니다. 변수는 1)initializer op를 실행하거나, 2)저장된 파일로부터 변수를 다시 저장(restoring)하거나, 3)간단하게 변수에 값을 할당하는 assign Op을 실행하여 초기화 할 수 있습니다. 사실, 변수 initializer op는 단지 변수의 초기값을 할당하는 assign Op 입니다.

# Launch the graph in a session.
with tf.Session() as sess:
    # Run the variable initializer.
    sess.run(w.initializer)
    # ...you now can run ops that use the value of 'w'...


가장 일반적인 초기화 방법은 모든 변수를 초기화 할 graph에 편의 함수인 initialize_all_variables()으로 Op를 추가하는 것 입니다. 그런 다음 graph를 실행한 후 Op를 실행합니다.

# Add an Op to initialize all variables.
init_op = tf.initialize_all_variables()

# Launch the graph in a session.
with tf.Session() as sess:
    # Run the Op that initializes all variables.
    sess.run(init_op)
    # ...you can now run any Op that uses variable values...


다른 변수의 결과로 초기되는 변수를 만들어야한다면, 다른 변수의 initialized_value()를 사용합니다. 이것은 변수가 올바는 순서로 초기화되도록 합니다.


모든 변수들은 자동적으로 그들이 만들어진 graph에 쌓입니다. 기본적으로, 생성자는 그래프 컬렉션(graph collection) GraphKeys.VARIABLES에 변수를 추가합니다. 편의 함수인 all_variables()은 컬렉션의 내용을 반환합니다.


머신 러닝 모델을 만들 때, 학습 가능한 모델 매개변수를 가지고 있는 변수와 global step 변수과 같이 학습 단계를 계산하기 위한 다른 변수로 구분하는 것은 종종 편리합니다. 이것을 더 쉽게 하기위해, 변수 생성자는 trainable=<bool> 매개변수를 지원합니다. True일 때 새로운 변수는 그래프 컬렉션 GraphKeys.TRAINABLE_VARIABLES에 추가됩니다. 편의 함수 trainable_variables()는 이 컬렉션의 내용을 반환합니다. 다양한 Optimizer 클래스는 이 컬렉션을 최적화(optimize) 변수의 기본 리스트로 사용합니다.


Creating a variable.


출처: Variables



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Constant, Sequence and Random Seed

(텐서플로우 상수, 시퀀스, 그리고 난수)

참고 : Tensor를 인자로 받는 함수들은 tf.convert_to_tensor의 인자로 들어갈 수 있는 값들 또한 받을 수 있습니다.


상수값 텐서

TensorFlow는 상수를 생성할 수 있는 몇가지 연산을 제공합니다.


tf.zeros(shape, dtype=tf.float32, name=None)


모든 원소의 값이 0인 텐서를 생성합니다.


이 연산은 모든 원소의 값이 0이고, shape shape을 가진 dtype타입의 텐서를 반환합니다.


예시:

tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

인자:
  • shape: 정수 리스트 또는 int32타입의 1-D(1-Dimension) Tensor.
  • dtype: 반환되는 Tensor의 원소 타입.
  • name: 연산의 명칭 (선택사항).
반환값:

모든 원소의 값이 0인 Tensor.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.zeros 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const = tf.zeros([3, 4], tf.int32)
In [4]: tfutil.print_constant(const)
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

tf.zeros_like(tensor, dtype=None, name=None)


모든 원소의 값이 0인 텐서를 생성합니다.


하나의 텐서(tensor)가 주어졌을 때, 이 연산은 모든 원소의 값이 0이고 tensor와 같은 타입과 shape을 가진 텐서를 반환합니다. 선택적으로, dtype을 사용해서 새로운 타입을 지정할 수도 있습니다.


예시:

# 'tensor' is [[1, 2, 3], [4, 5, 6]]

tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]]

인자:
  • tensor: 하나의 Tensor.
  • dtype: 반환되는 Tensor의 타입. float32, float64, int8, int16, int32, int64, uint8, complex64, or complex128만 가능합니다.
  • name: 연산의 명칭 (선택사항).
반환값:

모든 원소의 값이 0인 Tensor.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.zeros_like 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const = tf.constant([[1, 2, 3], [1, 2, 3]])
In [4]: tfutil.print_constant(const)
[[1 2 3]
 [1 2 3]]
In [5]: const = tf.zeros_like(const)
In [6]: tfutil.print_constant(const)
[[0 0 0]
 [0 0 0]]

tf.ones(shape, dtype=tf.float32, name=None)


모든 원소의 값이 1인 텐서를 생성합니다.


이 연산은 모든 원소의 값이 1이고, shape shape을 가진 dtype타입의 텐서를 반환합니다.


예시:

tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]

인자:
  • shape: 정수 리스트 또는 int32타입의 1-D(1-Dimension) Tensor.
  • dtype: 반환되는 Tensor의 원소 타입.
  • name: 연산의 명칭 (선택사항).
반환값:

모든 원소의 값이 1인 Tensor.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.zeros 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const = tf.ones([2, 3], tf.int32)
In [4]: tfutil.print_constant(const)
[[1 1 1]
 [1 1 1]]

tf.ones_like(tensor, dtype=None, name=None)


모든 원소의 값이 1인 텐서를 생성합니다.


하나의 텐서(tensor)가 주어졌을 때, 이 연산은 모든 원소의 값이 1이고 tensor와 같은 타입과 shape을 가진 텐서를 반환합니다. 선택적으로, dtype을 사용해서 새로운 타입을 지정할 수도 있습니다.


예시:

# 'tensor' is [[1, 2, 3], [4, 5, 6]]

tf.zeros_like(tensor) ==> [[1, 1, 1], [1, 1, 1]]

인자:
  • tensor: 하나의 Tensor.
  • dtype: 반환되는 Tensor의 타입. float32, float64, int8, int16, int32, int64, uint8, complex64, or complex128만 가능합니다.
  • name: 연산의 명칭 (선택사항).
반환값:

모든 원소의 값이 1인 Tensor.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.ones_like 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const = tf.constant([[1, 2, 3], [1, 2, 3]])
In [4]: tfutil.print_constant(const)
[[1 2 3]
 [1 2 3]]
In [5]: const = tf.ones_like(const)
In [6]: tfutil.print_constant(const)
[[1 1 1]
 [1 1 1]]

tf.fill(dims, value, name=None)


스칼라값으로 채워진 텐서를 생성합니다.


이 연산은 dims shape의 텐서를 만들고 value로 값을 채웁니다.


예시:

# Output tensor has shape [2, 3].

fill([2, 3], 9) ==> [[9, 9, 9]

                     [9, 9, 9]]

인자:
  • dims: int32타입의 Tensor. 1-D(1-Dimension)이며 반환값 텐서의 shape을 나타냅니다.
  • value: 스칼라 값을 갖는 Tensor. 반환값 텐서에 채워지는 값입니다.
  • name: 연산의 명칭 (선택사항).
반환값:

value와 같은 타입을 가진 Tensor.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.fill 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const = tf.fill([2, 3], 9)
In [4]: tfutil.print_constant(const)
[[9 9 9]
 [9 9 9]]

tf.constant(value, dtype=None, shape=None, name='Const')


상수 텐서를 생성합니다.


결과값 텐서는 value인자와 (선택적인) shape에 의해 결정됨으로써 dtype타입의 값으로 채워집니다. (아래 예시를 보세요.)


인자 value는 상수 또는 dtype타입을 가진 값들의 리스트가 될 수 있습니다. 만약 value가 리스트라면, 리스트의 길이는 shape인자에 의해 나올 수 있는 원소들의 갯수와 같거나 작아야 합니다. 리스트의 길이가 shape에 의해 정해지는 원소들의 갯수보다 적을 경우, 리스트의 마지막 원소가 나머지 엔트리를 채우는데 사용됩니다.


shape인자는 선택사항입니다. 만약 이 인자가 존재할 경우, 이는 결과값 텐서의 차원을 결정합니다. 그 외에는, value의 shape을 그대로 사용합니다.


만약 dtype인자가 결정되지 않을 경우에는, value로부터 타입을 추론하여 사용합니다.


예시:

# Constant 1-D Tensor populated with value list.

 tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]


# Constant 2-D tensor populated with scalar value -1.

 tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]

                                              [-1. -1. -1.]]

인자:
  • value: 반환 타입 dtype의 상수값 (또는 리스트).
  • dtype: 결과값 텐서 원소들의 타입.
  • shape: 결과값 텐서의 차원 (선택사항).
  • name: 텐서의 명칭 (선택사항).
반환값:

상수 Tensor.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.constant 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const1 = tf.constant([1, 2, 3, 4, 5, 6, 7])
In [4]: tfutil.print_constant(const1)
[1 2 3 4 5 6 7]
In [5]: const2 = tf.constant(-1.0, shape=[2, 3])
In [6]: tfutil.print_constant(const2)
[[-1. -1. -1.]
 [-1. -1. -1.]]


시퀀스

tf.linspace(start, stop, num, name=None)

tf.linspace(start, stop, num, name=None)

구간 사이의 값들을 생성합니다.


start부터 시작해서 생성된 num개의 고르게 분포된 값들의 시퀀스입니다. 만약 num > 1이면, 시퀀스의 값들은 stop - start / num - 1씩 증가되며, 마지막 원소는 stop값과 같아집니다.


예시:

tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0  11.0  12.0]

인자:
  • start: float32또는 float64타입의 Tensor. 구간의 첫번째 엔트리입니다.
  • stop: start와 같은 타입을 가진 Tensor. 구간의 마지막 엔트리입니다.
  • num: int32타입의 Tensor. 생성할 값들의 갯수입니다.
  • name: 연산의 명칭 (선택사항).
반환값:

start와 같은 타입을 가진 Tensor. 생성된 값들은 1-D입니다.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.linspace 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const = tf.linspace(10.0, 12.0, 3, name="linspace")
In [4]: tfutil.print_constant(const)
[ 10.  11.  12.]

tf.range(start, limit=None, delta=1, name='range')


정수 시퀀스를 생성합니다.


start부터 시작하여 limit까지 (limit는 포함하지 않음) delta의 증가량만큼 확장하며 정수 리스트를 생성합니다.


파이썬의 내장 함수인 range와 유사하며, start의 기본값은 0이고, 즉 range(n) = range(0, n)입니다.


예시:

# 'start' is 3

# 'limit' is 18

# 'delta' is 3

tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]


# 'limit' is 5

tf.range(limit) ==> [0, 1, 2, 3, 4]

인자:
  • start: int32타입의 스칼라 값(0-D)입니다. 시퀀스의 첫번째 엔트리이며, 기본값은 0입니다.
  • limit: int32타입의 스칼라 값(0-D)입니다. 시퀀스의 상한이며, 시퀀스에 포함되지 않습니다. (exclusive)
  • delta: A 0-D Tensor (scalar) of type int32. Optional. Default is 1. Number that increments start. int32타입의 스칼라(0-D) 텐서입니다. 선택적인 인자이며, 기본값은 1입니다. start를 증가시키는 수입니다.
  • name: 연산의 명칭 (선택사항).
반환값:

1-D의 int32타입을 갖는 Tensor.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.range 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const1 = tf.range(3, 18, 3)
In [4]: tfutil.print_constant(const1)
[ 3  6  9 12 15]
In [5]: const2 = tf.range(5)
In [6]: tfutil.print_constant(const2)
[0 1 2 3 4]


난수 텐서

TensorFlow는 서로 다른 분포를 가진 난수 텐서들을 생성하는 여러가지 연산들을 제공합니다. 난수 연산들은 상태를 가지며 , 계산될 때마다 새로운 난수를 생성합니다.


이러한 함수들의 seed 키워드 인자는 그래프 수준의 난수 시드값과 함께 작용합니다. set_random_seed를 사용하는 그래프 수준의 시드 또는 연산 수준의 시드를 바꾸는 것은 이러한 연산들의 기본 시드값을 바꿀 것입니다. 연산 수준과 그래프 수준의 난수 시드 사이의 상호작용에 대해 자세히 알고 싶다면 set_random_seed를 참고하십시오.


예시:


# Create a tensor of shape [2, 3] consisting of random normal values, with mean
# -1 and standard deviation 4.
norm = tf.random_normal([2, 3], mean=-1, stddev=4)

# Shuffle the first dimension of a tensor
c = tf.constant([[1, 2], [3, 4], [5, 6]])
shuff = tf.random_shuffle(c)

# Each time we run these ops, different results are generated
sess = tf.Session()
print(sess.run(norm))
print(sess.run(norm))

# Set an op-level seed to generate repeatable sequences across sessions.
norm = tf.random_normal([2, 3], seed=1234)
sess = tf.Session()
print(sess.run(norm))
print(sess.run(norm))
sess = tf.Session()
print(sess.run(norm))
print(sess.run(norm))


또 다른 난수값을 사용하는 일반적인 사례는 변수들의 초기화입니다. 이 또한 Variables How To에서 볼 수 있습니다.


# Use random uniform values in [0, 1) as the initializer for a variable of shape
# [2, 3]. The default type is float32.
var = tf.Variable(tf.random_uniform([2, 3]), name="var")
init = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init)
print(sess.run(var))


출처: 상수, 시퀀스, 그리고 난수


tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)


정규분포로부터의 난수값을 반환합니다.

인자:
  • shape: 정수값의 1-D 텐서 또는 파이썬 배열. 반환값 텐서의 shape입니다.
  • mean: 0-D 텐서 또는 dtype타입의 파이썬 값. 정규분포의 평균값.
  • stddev: 0-D 텐서 또는 dtype타입의 파이썬 값. 정규분포의 표준 편차.
  • dtype: 반환값의 타입.
  • seed: 파이썬 정수. 분포의 난수 시드값을 생성하는데에 사용됩니다. 동작 방식은 set_random_seed를 보십시오.
  • name: 연산의 명칭 (선택사항).
반환값:

정규 난수값들로 채워진 shape으로 정해진 텐서.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.random_normal 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: norm1 = tf.random_normal([2, 3], mean=-1, stddev=4)
In [4]: tfutil.print_constant(norm1)
[[ 3.35130119 -7.31051493 -4.19216442]
 [ 0.91765988 -2.39770412 -7.73829746]]
In [5]: norm2 = tf.random_normal([2, 3], seed=1234)
In [6]: tfutil.print_constant(norm2)
[[ 0.51340485 -0.25581399  0.65199131]
 [ 1.39236379  0.37256798  0.20336303]]

tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)


절단정규분포로부터의 난수값을 반환합니다.


생성된 값들은 평균으로부터 떨어진 버려지고 재선택된 두 개의 표준편차보다 큰 값을 제외한 지정된 평균과 표준 편차를 가진 정규 분포를 따릅니다.

인자:
  • shape: 정수값의 D-1 텐서 또는 파이썬 배열. 반환값 텐서의 shape입니다.
  • mean: 0-D 텐서 또는 dtype타입의 파이썬 값. 절단정규분포의 평균값.
  • stddev: 0-D 텐서 또는 파이썬 값. 절단정규분포의 표준 편차.
  • dtype: 반환값의 타입.
  • seed: 파이썬 정수. 분포의 난수 시드값을 생성하는데에 사용됩니다. 동작 방식은 set_random_seed를 보십시오.
  • name: 연산의 명칭 (선택사항).
반환값:

절단 정규 난수값들로 채워진 shape으로 정해진 텐서.



출처: 상수, 시퀀스, 그리고 난수



tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None)


균등분포로부터의 난수값을 반환합니다.


생성된 값들은 [minval, maxval]구간의 균등분포를 따릅니다. 하한 minval은 구간에 포함(included)되는 반면, 상한인 maxval은 포함되지 않습니다(excluded).


실수형의 경우, 기본 구간은 [0, 1)입니다. 정수형의 경우, 적어도 maxval은 명시적으로 지정되어야합니다.


정수형의 경우, maxval - minval가 2의 제곱수가 아니라면 정수 난수들은 한쪽으로 약간 치우칩니다. 치우침의 정도는 maxval - minval의 값이 반환값의 구간(2**32 또는 2**64)보다 훨씬 작을 경우엔 작습니다.

인자:
  • shape: 정수값의 D-1 텐서 또는 파이썬 배열. 반환값 텐서의 shape입니다.
  • minval: 0-D 텐서 또는 dtype타입의 파이썬 값. 난수값 생성 구간의 하한입니다. 기본값은 0입니다.
  • maxval: 0-D 텐서 또는 dtype타입의 파이썬 값. 난수값 생성 구간의 상한입니다. dtype이 실수형일 경우 기본값은 1입니다.
  • dtype: 반환값의 타입: float32, float64, int32, 또는 int64.
  • seed: 파이썬 정수. 분포의 난수 시드값을 생성하는데에 사용됩니다. 동작 방식은 set_random_seed를 보십시오.
  • name: 연산의 명칭 (선택사항).
반환값:

균등 난수값들로 채워진 shape으로 정해진 텐서.

예외:
  • ValueError: dtype이 정수형인데 maxval이 지정되지 않을 경우 발생합니다.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.random_uniform 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: norm = tf.random_uniform([2, 3], name="var")
In [4]: tfutil.print_constant(norm)
[[ 0.08737898  0.09874284  0.14296401]
 [ 0.25106776  0.87683988  0.44800055]]

tf.random_shuffle(value, seed=None, name=None)


값의 첫번째 차원을 기준으로 랜덤하게 섞어줍니다.


텐서는 0차원을 따라 섞이는데, 예를 들면 각 value[j]output[i]의 각 원소에 정확히 하나씩 매핑이됩니다. 예를 들면, 3x2 텐서의 경우 다음과 같은 매핑을 가질 수 있습니다.

[[1, 2],       [[5, 6],
 [3, 4],  ==>   [1, 2],
 [5, 6]]        [3, 4]]
인자:
  • value: 섞기 위한 텐서.
  • seed: 파이썬 정수. 분포의 난수 시드값을 생성하는데에 사용됩니다. 동작 방식은 set_random_seed를 보십시오.
  • name: 연산의 명칭 (선택사항).
반환값:

value의 첫번째 차원을 따라 섞인 value와 같은 타입과 shape을 가진 텐서.


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.random_shuffle 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: const = tf.constant([[1, 2], [3, 4], [5, 6]])
In [4]: tfutil.print_constant(const)
[[1 2]
 [3 4]
 [5 6]]
In [5]: shuff = tf.random_shuffle(const)
In [6]: tfutil.print_constant(shuff)
[[3 4]
 [5 6]
 [1 2]]

tf.random_crop(value, size, seed=None, name=None)


텐서를 주어진 사이즈만큼 랜덤하게 잘라냅니다.


균등하게 선택된 오프셋에서 value의 일부분을 size shape으로 잘라냅니다. value.shape >= size를 만족해야합니다.


만약 차원을 잘라낼 수 없다면 차원의 전체 크기를 보냅니다. 예를 들면, RGB 이미지는 size = [crop_height, crop_width, 3]을 가지고 잘라낼 수 있습니다.

인자:
  • value: 자르기 위한 입력 텐서.
  • size: value의 랭크값을 가진 1-D 텐서.
  • seed: 파이썬 정수. 분포의 난수 시드값을 생성하는데에 사용됩니다. 동작 방식은 set_random_seed를 보십시오.
  • name: 연산의 명칭 (선택사항).
반환값:

value와 같은 랭크값을 갖고 size shape을 갖는 잘려진 텐서


출처: 상수, 시퀀스, 그리고 난수



tf.multinomial(logits, num_samples, seed=None, name=None)


다항분포로부터 샘플을 뽑아줍니다.


예시:

samples = tf.multinomial(tf.log([[0.5, 0.5]]), 10)

samples has shape [1, 10], where each value is either 0 or 1.

samples = tf.multinomial([[1, -1, -1]], 10)

samples is equivalent to tf.zeros([1, 10], dtype=tf.int64).

인자:
  • logits: [batch_size, num_classes] shape을 갖는 2-D 텐서. 각 슬라이스 [i, :]는 모든 클래스에 대한 비정규화 로그 확률을 나타냅니다.
  • num_samples: 0-D. Number of independent samples to draw for each row slice. 0-D. 각 행 슬라이스를 뽑기위한 독립적인 샘플의 갯수.
  • seed: 파이썬 정수. 분포의 난수 시드값을 생성하는데에 사용됩니다. 동작 방식은 set_random_seed를 보십시오.
  • name: 연산의 명칭 (선택사항).
반환값:

[batch_size, num_samples] shape의 샘플들


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.multinomial 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: mn1 = tf.multinomial(tf.log([[0.5, 0.5]]), 10)
In [4]: tfutil.print_constant(mn1)
[[0 1 1 0 1 0 0 1 1 0]]

tf.set_random_seed(seed)


그래프 수준의 난수 시드를 설정합니다.


난수 시드에 의존하는 연산들은 실제로 그래프 수준과 연산 수준의 두 가지 시드로부터 시드를 얻어냅니다. 이 연산은 그래프 수준의 시드를 설정합니다.


연산 수준의 시드와의 상호작용은 다음과 같습니다.

  1. 그래프 수준과 연산 시드가 모두 설정되어있지 않은 경우: 난수 시드는 이 연산을 위해 사용됩니다.
  2. 그래프 수준의 시드가 설정되어있고, 연산 시드는 설정되어있지 않은 경우, 시스템은 유일한 난수 시퀀스를 얻기위해 결정론적으로 그래프 수준의 시드와 함께 사용할 연산 시드를 선택합니다.
  3. 그래프 수준의 시드가 설정되어있지 않고 연산 시드만 설정되어있는 경우, 난수 시퀀스를 결정하기 위해 그래프 수준의 시드의 기본값과 지정된 연산 시드가 사용됩니다.
  4. 두 시드 모두 설정되어있을 경우, 난수 시퀀스를 결정하기 위해 두 시드가 함께 사용됩니다.

눈에 보이는 효과를 설명하기위해, 다음과 같은 예시들을 생각해봅시다:


세션간에 다른 시퀀스를 생성하기위해 그래프 수준과 연산 수준의 시드를 모두 설정하지 않습니다.


a = tf.random_uniform([1])
b = tf.random_normal([1])

print("Session 1")
with tf.Session() as sess1:
  print(sess1.run(a))  # generates 'A1'
  print(sess1.run(a))  # generates 'A2'
  print(sess1.run(b))  # generates 'B1'
  print(sess1.run(b))  # generates 'B2'

print("Session 2")
with tf.Session() as sess2:
  print(sess2.run(a))  # generates 'A3'
  print(sess2.run(a))  # generates 'A4'
  print(sess2.run(b))  # generates 'B3'
  print(sess2.run(b))  # generates 'B4'


세션간에 하나의 연산이 똑같이 반복가능한 시퀀스를 생성할 수 있도록, 연산 시드를 설정합니다.


a = tf.random_uniform([1], seed=1)
b = tf.random_normal([1])

# Repeatedly running this block with the same graph will generate the same
# sequence of values for 'a', but different sequences of values for 'b'.
print("Session 1")
with tf.Session() as sess1:
  print(sess1.run(a))  # generates 'A1'
  print(sess1.run(a))  # generates 'A2'
  print(sess1.run(b))  # generates 'B1'
  print(sess1.run(b))  # generates 'B2'

print("Session 2")
with tf.Session() as sess2:
  print(sess2.run(a))  # generates 'A1'
  print(sess2.run(a))  # generates 'A2'
  print(sess2.run(b))  # generates 'B3'
  print(sess2.run(b))  # generates 'B4'


모든 연산에 의해 생성된 난수 시퀀스들이 세션간 반복이 가능하게 하기위해서, 그래프 수준의 시드를 설정합니다.


tf.set_random_seed(1234)
a = tf.random_uniform([1])
b = tf.random_normal([1])

# Repeatedly running this block with the same graph will generate different
# sequences of 'a' and 'b'.
print("Session 1")
with tf.Session() as sess1:
  print(sess1.run(a))  # generates 'A1'
  print(sess1.run(a))  # generates 'A2'
  print(sess1.run(b))  # generates 'B1'
  print(sess1.run(b))  # generates 'B2'

print("Session 2")
with tf.Session() as sess2:
  print(sess2.run(a))  # generates 'A1'
  print(sess2.run(a))  # generates 'A2'
  print(sess2.run(b))  # generates 'B1'
  print(sess2.run(b))  # generates 'B2'


출처: 상수, 시퀀스, 그리고 난수


Tensorflow tf.multinomial 결과

# session 1

In [1]: import tensorflow as tf

In [2]: ru1 = tf.random_uniform([1])
In [3]: rn1 = tf.random_normal([1])
In [4]: with tf.Session() as sess1:
   ...:     print(sess1.run(ru1))
   ...:     print(sess1.run(ru1))
   ...:     print(sess1.run(rn1))
   ...:     print(sess1.run(rn1))
[ 0.41243613]
[ 0.77785075]
[ 1.29497552]
[-0.37886024]
In [5]: with tf.Session() as sess2:
   ...:     print(sess2.run(ru1))
   ...:     print(sess2.run(ru1))
   ...:     print(sess2.run(rn1))
   ...:     print(sess2.run(rn1))
[ 0.56656086]
[ 0.80175865]
[-1.03073514]
[-0.0781072]
# session 2

In [1]: import tensorflow as tf

In [2]: ru1 = tf.random_uniform([1], seed=1)
In [3]: rn1 = tf.random_normal([1])
In [4]: with tf.Session() as sess1:
   ...:     print(sess1.run(ru1))
   ...:     print(sess1.run(ru1))
   ...:     print(sess1.run(rn1))
   ...:     print(sess1.run(rn1))
[ 0.23903739]
[ 0.22267115]
[-0.69122458]
[ 1.63219154]
In [5]: with tf.Session() as sess2:
   ...:     print(sess2.run(ru1))
   ...:     print(sess2.run(ru1))
   ...:     print(sess2.run(rn1))
   ...:     print(sess2.run(rn1))
[ 0.23903739]
[ 0.22267115]
[ 1.65277016]
[ 0.89793456]
# session 3

In [1]: import tensorflow as tf

In [2]: tf.set_random_seed(1234)

In [3]: ru1 = tf.random_uniform([1])
In [4]: rn1 = tf.random_normal([1])
In [45]: with tf.Session() as sess1:
   ...:     print(sess1.run(ru1))
   ...:     print(sess1.run(ru1))
   ...:     print(sess1.run(rn1))
   ...:     print(sess1.run(rn1))
[ 0.1211642]
[ 0.41471958]
[-1.76099801]
[-1.82982743]
In [6]: with tf.Session() as sess2:
   ...:     print(sess2.run(ru1))
   ...:     print(sess2.run(ru1))
   ...:     print(sess2.run(rn1))
   ...:     print(sess2.run(rn1))
[ 0.1211642]
[ 0.41471958]
[-1.76099801]
[-1.82982743]



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API DocumentPython API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Building Graphs (텐서플로우 그래프 생성)


[TOC] Classes and functions for building TensorFlow graphs







이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤