Tensorflow函数--1

版权声明:转载请注明出处。 https://blog.csdn.net/Xin_101/article/details/83005106

1 tf.constant()

  • tf.constant(value, shape=None, dtype=none, name=‘Const’ ,verify_shape=False)
import tensorflow as tf 

a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
c = tf.constant([1, 2, 3, 4, 5, 6])
d = tf.constant([[1,2,3],[4,5,6]])
result = a + b
print(a)
print(result)
print(c.shape)
print(c.get_shape())
print(tf.shape(c))
print(d)
print(d.shape)
print(d.get_shape())
print(tf.shape(d))

with tf.Session() as sess:
	print(sess.run(result))
	print(a.eval())

【结果】

Tensor("a:0", shape=(2,), dtype=float32)
Tensor("add:0", shape=(2,), dtype=float32)
(6,)
(6,)
Tensor("Shape:0", shape=(1,), dtype=int32)
Tensor("Const_1:0", shape=(2, 3), dtype=int32)
(2, 3)
(2, 3)
Tensor("Shape_1:0", shape=(2,), dtype=int32)
Tensor("Shape:0", shape=(1,), dtype=int32)
[ 3.  5.]
[ 1.  2.]

【解读】

0.tf.constant参数说明:value表示给变量赋值,值可为数值或列表;shape为变量维度(行,列)。
1.tf.constant是一个计算,结果是一个张量,如print(a),结果为Tensor("a:0", shape=(2,), dtype=float32)。其中,a:0是属性名字,张量的唯一标识符。
2.张量的维度:c.shape=c.get_shape(),tf.shape(c)是c的整体结构。
3.维度shape(row, column)。d的shape,为(2, 3),2行3列。
4.tf.Session()执行定义的运算。sess.run运行计算,可通过tf.Tensor.eval函数获取张量的取值。如a.eval(),result.eval()。

2 Session()

  • 创建会话的方式
  1. 创建默认会话
sess = tf.Session()
with sess.as_default():
	print(result.eval())
  1. 交互会话
sess = tf.InteractiveSession()
print(result.eval())
sess.close()
  1. 上下文管理器会话
with tf.Session() as tf:
	print(result.eval())
	print(sess.run(result))
  1. ConfigProto Protocol Buffer会话
config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)
sess1 = tf.InteractiveSession(config=config)
sess2 = tf.Session(config=config)

3 ConfigProto

  • ConfigProto(allow_soft_placement=True, log_device_placement=True)
1.ConfigProto可配置类似并行的线程数,GPU分配策略、运算超时时间等参数。
2.allow_soft_placement设为True,GPU上的运算可移植到CPU上,不会报错。
3.log_device_placement生产环境中,设置为False减少日志量。

4 tf.Variable

Tensorflow通过变量名称创建或获取变量。

  • tf.Variable(initializer,name)
0. 参数说明:initializer初始化参数,name参数名称,唯一标识符。
1. 作用:声明变量,保存和更新变量。
2. v = tf.Variable(tf.random_normal(shape=[2, 2], stddev=1), name="v")

5 tf.get_variable

  • tf.get_variable(name, shape=None,dtype=tf.float32,initializer=None, regularizer=None,trainable=True,collections=None)
0. 获取已存在的变量,如果不存在就创建一个变量。
1. 

持续更新ing

猜你喜欢

转载自blog.csdn.net/Xin_101/article/details/83005106