[PYTHON] TensorFlow API memo

API of TensorFlow

Make a note of what you've researched about the TensorFlow API. I will add it every time I check it. Confirmed with version 1.21.

Reference link

-Installing TensorFlow on Windows was easy even for Python beginners -[Explanation for beginners] TensorFlow basic syntax and concept -[Explanation for beginners] TensorFlow tutorial MNIST (for beginners) -[Introduction to TensorBoard] Visualize TensorFlow processing to deepen understanding -[Introduction to TensorBoard: image] TensorFlow Visualize image processing to deepen understanding -[Introduction to TensorBoard: Projector] Make TensorFlow processing look cool -Visualize TensorFlow tutorial MNIST (for beginners) with TensorBoard -[Explanation for beginners] TensorFlow Tutorial Deep MNIST -Install matplotlib with Jupyter Notebook and display graph -Yuki Kashiwagi's facial features to understand TensorFlow [Part 1]

shape

Description

It returns the number of elements in the Tensor dimension. I've seen the size of the image file.

Basic syntax

shape(
    input,
    name=None,
    out_type=tf.int32
)

Example 1

Returns the shape of a one-dimensional three-element array

import tensorflow as tf
sess = tf.InteractiveSession()
print(sess.run(tf.shape((tf.range(3)))))

result

[3]

Example 2

Reshape 0 to 11 and store in Tensor. Returns that Shape.

import tensorflow as tf
sess = tf.InteractiveSession()
three_dim = tf.reshape(tf.range(6),[1,2,3])
print(sess.run(three_dim))
print(sess.run(tf.shape(three_dim)))

Result (top is Tensor content, bottom is shape result)

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

[1 2 3]

range

Description

It will make the numbers in order. It comes in handy when checking the operation.

Basic syntax

range(limit, delta=1, dtype=None, name='range')
range(start, limit, delta=1, dtype=None, name='range'))

Example 1

Store 0 to 11 in Tensor

import tensorflow as tf
sess = tf.InteractiveSession()
print(sess.run(tf.range(12)))

result

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

Example 2

Reshape 0 to 11 and store in Tensor. This method is useful for checking the operation.

import tensorflow as tf
sess = tf.InteractiveSession()
print(sess.run(tf.reshape(tf.range(12), [3,4])))

result

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

reshape

Description

Convert tensor format.

Basic syntax

reshape(
    tensor,
    shape,
    name=None
)

Example 1

Convert a 1D array from 0 to 11 to a 2x6 2D array

import tensorflow as tf
sess = tf.InteractiveSession()
print(sess.run(tf.reshape(tf.range(12), [2,6])))

result

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

Example 2

Convert a 1D array from 0 to 11 to a 2x3x2 3D array

import tensorflow as tf
sess = tf.InteractiveSession()
print(sess.run(tf.reshape(tf.range(12), [2,3,2])))

result

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

[[ 6 7] [ 8 9] [10 11]]]

Example 3

Convert a 1D array from 0 to 11 to a 2x3x2 3D array (using -1) -1 means a wildcard and can only be used once (do not use it like [-1, -1, 2]). In this example, 12 variables are set to $ 12 ÷ 2 ÷ 2 = 3 $ and 3 is calculated.

import tensorflow as tf
sess = tf.InteractiveSession()
print(sess.run(tf.reshape(tf.range(12), [2,-1,2])))

result

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

[[ 6 7] [ 8 9] [10 11]]]

transpose

Description

Convert the order of tensors. It is easy to understand in [TensorFlow] View API document -Math edition-.

Basic syntax

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

Example 1

Permutation of a 2x6 2D array from 0 to 11. Since it is two-dimensional, it is a simple matrix transformation.

import tensorflow as tf
sess = tf.InteractiveSession()

x = (tf.reshape(tf.range(12), [-1,2]))

print(sess.run(x))
print(sess.run(tf.transpose(x)))

result

$ x $ Tensor

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

The result of transposing $ x $

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

Example 2

Ordering of a 4-dimensional array from 0 to 11. The order is specified by perm. In this example, the original Tensor is sorted in the order of 3D, 0D, 1D, and 2D.

import tensorflow as tf
sess = tf.InteractiveSession()
y = (tf.reshape(tf.range(12), [2,2,1,3]))

print(sess.run(y))
print(sess.run(tf.transpose(y, perm=[3,0,1,2])))

result

$ y $ Tensor

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

The result of transposing $ y $

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

truncated_normal

Description

Returns random numbers limited to up to twice the standard deviation according to a normal distribution.

Basic syntax

truncated_normal(
    shape,
    mean=0.0,
    stddev=1.0,
    dtype=tf.float32,
    seed=None,
    name=None
)

Example

Create 300 million random numbers with standard deviation of 0.1 and display them as a histogram.

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
sess = tf.InteractiveSession()
x = sess.run(tf.truncated_normal([30000], stddev=0.1))
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.hist(x, bins=100)
ax.set_title('Histogram tf.truncated_normal')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()

01.truncated_normal01.JPG

This is a reference (random_normal, normal normal distribution) 01.truncated_normal02.JPG

tf.app.run

Description

Function wrapper. If the argument main is None, main.main is executed. It seems to be convenient when calling with a command. Although it is in English, it is described in detail in Stackoverflow.

Basic syntax

run(
    main=None,
    argv=None
)

tf.summary.scalar

Description

Output to TensorBoard graph.

Basic syntax

scalar(
    name,
    tensor,
    collections=None
)

Example

Output the value of $ x + y $ to TensorBoard. Compare with or without tf.summary.scalar

import tensorflow as tf
sess = tf.InteractiveSession()

#TensorBoard information output directory
log_dir = '/tmp/tensorflow/mnist/logs/try01'

#Delete the specified directory if it exists and recreate it
if tf.gfile.Exists(log_dir):
    tf.gfile.DeleteRecursively(log_dir)
tf.gfile.MakeDirs(log_dir)

#1 with a constant+ 2
x = tf.constant(1, name='x')
y = tf.constant(2, name='y')
z_out    = x + y
z_no_out = x + y

#Output z on the graph with this command
tf.summary.scalar('z', z_out)

#Draw a graph with SummaryWriter
summary_writer = tf.summary.FileWriter(log_dir , sess.graph)

#Run
print(sess.run(z_out))
print(sess.run(z_no_out))

#SummaryWriter closed
summary_writer.close()

Result (left is when tf.summary.scalar is used, right is not)

tf.summary.scalar_example.png

Recommended Posts

TensorFlow API memo
TensorFlow API memo (Python)
Tensorflow API: tf.truncated_normal
Tensorflow API: FLAGS
Tensorflow API: tf.reverse
[TF] About Tensorflow API
Logo detection using TensorFlow Object Detection API
Install tensorflow in Docker (LINUX) (memo)
Data acquisition memo using Backlog API
gzip memo
Raspberry-pi memo
Pandas memo
HackerRank memo
Python memo
python memo
graphene memo
pyenv memo
Matplotlib memo
pytest memo
sed memo
Python memo
Install Memo
BeautifulSoup4 memo
tomcat memo
Generator memo.
psycopg2 memo
Python memo
SSH memo
Tensorflow Glossary
tensorflow mnist_deep.py
Memo: rtl8812
pandas memo
TensorFlow tutorial tutorial
Shell memo
Python memo
Pycharm memo
Python memo
Python --bitfinex public API memo --ticker, trades acquisition
Find polynomial approximations using TensorFlow 2.x Low-level API