tensorflow中张量、常量、变量、占位符

引言

从实例出发

#先导入TensorFlow
import tensorflow as tf

# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')

with tf.Session() as sess:
    # Run the tf.constant operation in the session
    output = sess.run(hello_constant)
    print(output)

有人会奇怪为什么不直接输出“hello world”,其实在tensorflow里面有它自己的 一套。

正文

1.tensor

在tensorflow中,数据是被封装在tensor对象中的。tensor是张量的意思,即包含从0到任意维度的张量。常数是0维度的张量,向量是1维度的张量,矩阵是二维度的张量,以及还有多维度的张量。

# tensor1 是一个0维的 int32 tensor
tensor1 = tf.constant(1234) 
# tensor2 是一个1维的 int32 tensor
tensor2 = tf.constant([123,456,789]) 
 # tensor3 是一个二维的 int32 tensor
tensor3 = tf.constant([ [123,456,789], [222,333,444] ])

2.tf.constant

constant函数提供在tensorflow中定义常量(不可更改的张量)的方法

如:

tensor_constant = tf.constant([1,2,3,4)

3.tf.Variable

tensorflow中的变量是通过Variable类来实现的。tensorflow中需要定义为变量的包括训练过程中的输入数据,输出数据,以及控制从输入到输出的学习机制,即网络参数。输入输出数据在tf中是用placeholder占位符来定义的,网络参数是用tf.Variable来定义的。

4.tf.placeholder

用于声明一个张量的数据格式,告诉系统这里会有一个这种格式的张量,但是还没有传入具体的值。

如:

X = tf.placeholder("float", shape=[None, 100])

上面声明了一个张量X,数据类型是float,100列,行数不确定。

5.tf.Session

以上部分都是搭建一个计算图的代码,在tf中,先搭建好计算图,然后再启动session,运行定义好的图。

import tensorflow as tf

x = tf.placeholder("string")
with tf.Session() as sess:
    output = sess.run(x, feed_dict={x : "run the map"})
    print(output)

通过上面的例子我们明白了如何使用占位符,首先定义x为占位符,然后运行的时候将想要传入的值传给x。

结尾

参考

https://blog.csdn.net/dcrmg/article/details/79016107

https://blog.csdn.net/fei13971414170/article/details/73309106/

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值