import tensorflow as tf
x = tf.Variable([2,34,56,33]) #创建变量x,为一个array
print(x) #查看x的shape,不是x的值。结果是: <tf.Variable 'Variable_3:0' shape=(4,) dtype=int32_ref>
with tf.Session() as sess :
... sess.run(x.initializer) #运行变量的initializer。调用op之前,所有变量都应被显式地初始化过。
... sess.run(x) #查看x的值,结果是:array([2, 34, 56,33],dtype=int32)
* 用 with 记得:和 sess.run() 前 需要 Tab (界面上显示为...)
y = tf.Variable(tf.random_uniform([2, 1],)) #初始化一个形状为[2,1]的张量 ,两个 一维数组 [ [1],[3] ]
y = tf.Variable(tf.random_uniform([2, 2],)) #初始化一个形状为[2,2]的张量 ,两个 维数组 [ [1,3],[3,4] ]
y = tf.Variable(tf.random_normal([20, 10], stddev=0.35)) #以标准差0.35的正太分布初始化一个形状为[20,10]的张量
tf.constant()函数定义:
def constant(value, dtype=None, shape=None, name="Const", verify_shape=False)
value: 符合tf中定义的数据类型的常数值或者常数列表;
dtype:数据类型,可选;
shape:常量的形状,可选;
name:常量的名字,可选;
verify_shape:常量的形状是否可以被更改,默认不可更改;
constant()函数提供在tensorflow中定义常量(不可更改的张量)的方法。
例如:
tensor_constant1 = tf.constant([1,2,3,4])
0维的叫做常数,1维的叫做向量,二维叫做矩阵,多维度的就直接叫张量
# tensor1 是一个0维的 int32 tensor
tensor1 = tf.constant(1314)
# tensor2 是一个1维的 int32 tensor
tensor2 = tf.constant([123,456,789])
# tensor3 是一个二维的 int32 tensor
tensor3 = tf.constant([ [123,456,789], [222,333,444] ])
# tensor3 是一个多维的 int32 tensor
tensor3 = tf.constant([ [123,456,789], [222,333,444] ,[222,333,444]])
tf.placeholder()函数定义:
def placeholder(dtype, shape=None, name=None)
dtype:表示tensorflow中的数据类型,如常用的tf.float32,tf.float64等数值类型;
shape:表示数据类型,默认的None是一个一维的数值,shape=[None,5],表示行不定,列是5;
name:张量名称;
placeholder()又叫占位符,用于声明一个张量的数据格式,告诉系统这里会有一个这种格式的张量,但是还没有给定具体数值,具体的数值要在正式运行的时候给到。占位变量是一种TensorFlow用来解决读取大量训练数据问题的机制,它允许你现在不用给它赋值,随着训练的开始,再把训练数据传送给训练网络学习。
例如:
X = tf.placeholder(tf.float32, shape = [None, 100 * 100])
以上声明一个张量并赋值给X,数据类型是tf.float32,大小是None*100*100,None表示数量不定,tensorflow会根据运行时候具体情况调整。
x = tf.placeholder(tf.string)
y = tf.placeholder(tf.int32)
z = tf.placeholder(tf.float32)
with tf.Session() as sess:
output = sess.run(x, feed_dict={x: 'Test String', y: 123, z: 45.67})
因篇幅问题不能全部显示,请点此查看更多更全内容