tensorflow 常用基本函数整理
tf.placeholder(dtype, shape=None, name=None)
参数:
dtype:数据类型。常用的是tf.float32, tf.float64等数值类型
shape:数据形状。默认是None,就是一维值,也可以是多维,比如[2,3], [None, 3]表示列是3,行不定
name:名称。
# 定义
x = tf.placeholder(tf.float32, shape=(1024, 1024))
# 执行,利用feed_dict的字典结构给placeholdr变量“喂数据”
y = tf.add(x, x)
with tf.Session() as sess:
# print(sess.run(y)) # ERROR: 此处x还没有赋值.
a = np.random.rand(1024, 1024)
print(sess.run(y, feed_dict={x: a}))
tf.constant()
定义
tf.constant(
value,
dtype=None,
shape=None,
name='Const',
verify_shape=False
)
创建一个常数张量
import tensorflow as tf
import numpy as np
a = tf.constant([1, 2, 3, 4, 5, 6, 7])
b = tf.constant(-1.0, shape=[2, 3])
c = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
d = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
e = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3])
with tf.Session() as sess:
print("a =", sess.run(a))
print("b =", sess.run(b))
print("c =", sess.run(c))
print("d =", sess.run(d))
print("e =", sess.run(e))
a = [1 2 3 4 5 6 7]
b = [[-1. -1. -1.]
[-1. -1. -1.]]
c = [[1 2 3]
[4 5 6]]
d = [[ 7 8]
[ 9 10]
[11 12]]
e = [[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
tf.Varialbe
Tensorflow中用于定义变量,这个变量能够保持到程序结束。
在深度学习中,常创建变量来保存权重等参数。
变量在使用前必须初始化。
tf.Variable是一个类,它实例化的对象有下面这些属性:
x = tf.Variable() # 实例化
x.initializer # 初始化单个变量
x.value() # 读取op
x.assign() # 写入op
x.assign_add() # 更多op
x.eval() # 输出变量内容
变量的定义和初始化:
import tensorflow as tf
# 形状为2*3的正态分布,均值为0,标准差为2; seed设定后每次随机生成的值相同
weights1 = tf.Variable(tf.random_normal([2, 3], stddev = 2, seed = 1))
# 形状为2*3的正态分布,均值为0,标准差为2; seed设定后每次随机生成的值不相同
weights2 = tf.Variable(tf.random_normal([2, 3], mean = 1, stddev = 2))
# 使用常数来设置偏置项(bias)初始值; 生成长度为3,值为0
biases = tf.Variable(tf.zeros([3]))
# 通过其他变量设置初始值
w2 = tf.Variable(weights1.initialized_value())
# 通过tf.global_variables_initializer函数全部初始化
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print("weights1=", sess.run(weights1))
print("weights2=", sess.run(weights2))
print("biases=", sess.run(biases))
print("w2=", sess.run(w2))
weights1= [[-1.6226364 2.9691975 0.13065875]
[-4.8854084 0.1984968 1.1824486 ]]
weights2= [[1.5604866 2.4487138 1.8684036]
[2.9444995 1.3254981 2.5650797]]
biases= [0. 0. 0.]
w2= [[-1.6226364 2.9691975 0.13065875]
[-4.8854084 0.1984968 1.1824486 ]]
变量单独初始化:
W = tf.Variable(tf.zeros([784, 10]))
with tf.Session() as sess:
sess.run(W.initializer)
参考: https://blog.csdn.net/yjk13703623757/article/details/77075711