import tensorflow as tf
# Basic constant operations
# The value returned by the constructor represents the output
# of the Constant op.
a = tf.constant(2)
b = tf.constant(3)
# Launch the default graph.
with tf.Session() as sess:
print("a=2, b=3")
print("Addition with constants: %i" % sess.run(a+b))
print("Multiplication with constants: %i" % sess.run(a*b))
# Basic Operations with variable as graph input
# The value returned by the constructor represents the output
# of the Variable op. (define as input when running session)
# tf Graph input
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
# Define some operations
add = tf.add(a, b)
mul = tf.multiply(a, b)
# Launch the default graph.
with tf.Session() as sess:
# Run every operation with variable input
print("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))
# ----------------
# More in details:
# Matrix Multiplication from TensorFlow official tutorial
# Create a Constant op that produces a 1x2 matrix. The op is
# added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
matrix1 = tf.constant([[3., 3.]])
# Create another Constant that produces a 2x1 matrix.
matrix2 = tf.constant([[2.],[2.]])
# Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
# The returned value, 'product', represents the result of the matrix
# multiplication.
product = tf.matmul(matrix1, matrix2)
# To run the matmul op we call the session 'run()' method, passing 'product'
# which represents the output of the matmul op. This indicates to the call
# that we want to get the output of the matmul op back.
#
# All inputs needed by the op are run automatically by the session. They
# typically are run in parallel.
#
# The call 'run(product)' thus causes the execution of threes ops in the
# graph: the two constants and matmul.
#
# The output of the op is returned in 'result' as a numpy `ndarray` object.
with tf.Session() as sess:
result = sess.run(product)
print(result)
# ==> [[ 12.]]tf.placeholder(
dtype,
shape=None,
name=None
)# 可以理解为为定义一个张量并为其申请一块空间,并且,以此方式定义的张量必须通过函数参数feed_dict来赋值,Session.run(), Tensor.eval(), Operation.run()placeholder定义的张量不能直接用于值化运算。
tf.add(
x,
y,
name=None
)# 返回x+y的值,张量加法运算,x,y的shape必须一致tf.multiply(
x,
y,
name=None
)# 返回x*y的值,张量的乘法运算,shape必须一致run(
fetches,
feed_dict=None, #数据字典,字典的key与fetches中的计算图元素一一对应,并将value赋值给这些张量
options=None,
run_metadata=None
)sess.run(add, feed_dict={a: 2, b: 3}) #将2,3分别赋值给placeholder的a, b,然后执行add加法运算,得到结果tf.matmul(
a,
b,
transpose_a=False, # 矩阵转置
transpose_b=False,
adjoint_a=False, # 共轭矩阵
adjoint_b=False,
a_is_sparse=False, # 稀疏矩阵
b_is_sparse=False,
name=None
)# 矩阵乘法
本文介绍了使用TensorFlow进行基本运算的方法,包括常量运算、变量运算及矩阵乘法等核心操作。通过具体实例展示了如何定义张量、执行加法与乘法运算,并详细解释了tf.placeholder、tf.add、tf.multiply及tf.matmul等函数的应用。
529

被折叠的 条评论
为什么被折叠?



