Tensorflow | Constants |常用函数介绍

本文详细介绍了TensorFlow中创建常值张量的方法,包括使用tf.zeros、tf.ones、tf.fill及tf.constant等函数的具体操作与应用实例,帮助读者快速掌握这些基本张量操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据官网的帮助文档,介绍Constants类型的函数,方便自己学习和查看。若是有幸帮到别的朋友,深感荣幸。

常值张量

  • tf.zeros
    产生元素0
    格式:tf.zeros(shape, dtype=tf.float32, name=None)
    shape表示维数,dtype定义类型,name定义名称

例子:

tf.zeros(shape=[3, 4], dtype=int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
  • tf.zeros_like

产生类似与tensor的全0张量
格式:tf.zeros_like(tensor, dtype=None, name=None)
tensor是一个张量,dtype定义类型,name定义名称

例子:

# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]]
  • tf.ones

产生全是1的张量
格式:tf.ones(shape, dtype=tf.float32, name=None)
shape定义维度,dtype定义类型,name定义名称

例子:

tf.ones(shape=[2, 3], dtype=int32) ==> [[1, 1, 1], [1, 1, 1]]
  • tf.ones_like

产生类似与张量tensor的全1张量
格式:tf.ones_like(tensor, dtype=None, name=None)

tensor是一个张量,dtype定义类型,name定义名称

例子:

# 'tensor' is [[1, 2, 3], [4, 5, 6]]
tf.ones_like(tensor) ==> [[1, 1, 1], [1, 1, 1]]
  • tf.fill

填充,用value来填充shape=dims的张量

格式:tf.fill(dims,value,name=None)

dims定义维度,value给定数值,name定义名称

例子:

# output tensor shape needs to be [2, 3]
# so 'dims' is [2, 3]
tf.fill(dims, 9) ==> [[9, 9, 9]
                   [9, 9, 9]]
  • tf.constant

定义常数张量

格式:tf.constant(value,dtype=None,shape=None,name=’Const’)

value给定的值,dtype定义类型,shape定义维度,name定义名称

例子:

 # Constant 1-D Tensor populated with value list.
 tensor = tf.constant(value=[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(value=-1.0, shape=[2, 3]) => [[-1. -1. -1.]
                                                    [-1. -1. -1.]]
TensorFlow提供了两种保存训练模型的方式: 1. 使用Saver类来保存模型的参数变量,这种方式保存的是计算图的结构和参数变量的取值,可以在后续的程序中加载模型并继续训练或者使用模型进行预测。 ```python import tensorflow as tf # 定义计算图 x = tf.placeholder(tf.float32, shape=[None, 784], name='x') y = tf.placeholder(tf.float32, shape=[None, 10], name='y') W = tf.Variable(tf.zeros([784, 10]), name='W') b = tf.Variable(tf.zeros([10]), name='b') y_ = tf.nn.softmax(tf.matmul(x, W) + b, name='y_') cross_entropy = -tf.reduce_sum(y * tf.log(y_), name='cross_entropy') train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # 创建Saver对象 saver = tf.train.Saver() # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys}) # 保存模型 saver.save(sess, 'model/model.ckpt') ``` 2. 使用SavedModelBuilder类来保存模型的计算图和变量,这种方式保存的是计算图的结构、变量的取值以及计算图中的元数据,可以在后续的程序中加载模型并直接使用。 ```python import tensorflow as tf # 定义计算图 x = tf.placeholder(tf.float32, shape=[None, 784], name='x') y = tf.placeholder(tf.float32, shape=[None, 10], name='y') W = tf.Variable(tf.zeros([784, 10]), name='W') b = tf.Variable(tf.zeros([10]), name='b') y_ = tf.nn.softmax(tf.matmul(x, W) + b, name='y_') cross_entropy = -tf.reduce_sum(y * tf.log(y_), name='cross_entropy') train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # 创建SavedModelBuilder对象 builder = tf.saved_model.builder.SavedModelBuilder('model') # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys}) # 构建模型 tensor_info_x = tf.saved_model.utils.build_tensor_info(x) tensor_info_y_ = tf.saved_model.utils.build_tensor_info(y_) prediction_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs={'images': tensor_info_x}, outputs={'scores': tensor_info_y_}, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME) builder.add_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: prediction_signature }, main_op=tf.tables_initializer(), strip_default_attrs=True) # 保存模型 builder.save() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值