TensorFlow学習ノート:6、Tensorflowでa=(b+c)∗(c+2)を計算する


Tensorflowはgraphに基づく並列計算モデルの一例であり、Tensorflow計算a=(b+c)∗(c+2)で計算式を分割することができる.
d = b + c
e = c + 2
a = d * e

プログラミングは次のとおりです.
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 16:39:49 2019

@author: hadron
"""
# https://blog.csdn.net/hustqb/article/details/80222055
# Tensorflow   graph       
#     , Tensorflow  a=(b+c)∗(c+2)
#           :
# d = b + c
# e = c + 2
# a = d * e

import numpy as np
import tensorflow as tf

# TensorFlow ,  tf.constant()    ,    

#   ,    TensorFlow  ,   2
const = tf.constant(2.0, name='const')
#         b c
#    b       。TensorFlow           (placeholder),  tf.placeholder()  。
b = tf.placeholder(tf.float32, [None, 1], name='b')
#  tf.Variable()    ,   。
c = tf.Variable(1.0, dtype=tf.float32, name='c')

#   operation
d = tf.add(b, c, name='d')
e = tf.add(c, const, name='e')
a = tf.multiply(d, e, name='a')

# Tensorflow          ,     
#             
init_op = tf.global_variables_initializer()
#   graph     tf.Session()        (session)。session     graph   handle。
# session
with tf.Session() as sess:
	# 2.   init operation
	sess.run(init_op)
    # tensorflow                      
    # feed_dict       ,      
	a_out = sess.run(a, feed_dict={b: np.arange(0, 10)[:, np.newaxis]})
	print("Variable a is {}".format(a_out))

print("----------") 
#np.arange(0, 10)      [0 1 2 3 4 5 6 7 8 9]
print(np.arange(0, 10))    
#np.newaxis           ,       np.newaxis     
print(np.arange(0, 10)[:, np.newaxis])

実行結果
Variable a is [[ 3.]
 [ 6.]
 [ 9.]
 [12.]
 [15.]
 [18.]
 [21.]
 [24.]
 [27.]
 [30.]]
----------
[0 1 2 3 4 5 6 7 8 9]
[[0]
 [1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]
 [9]]