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

2023年7月20日09:09:27

引言

从实例出发

#先导入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/

  • 作者:耐耐~
  • 原文链接:https://blog.csdn.net/f156207495/article/details/82585547
    更新时间:2023年7月20日09:09:27 ,共 1313 字。