一、tensorflow基本使用
1、tf基本用法 import tensorflow as tf
①创建变量
tf.constant(val, dtype=None,shape=None,name='Const', verify_shape=False)
tf.fill(dims, value, name=None)shape, dtype=tf.float32, name=None)
tf.zeros_like(tensor, dtype=None, name=None) tf.ones(shape, dtype=tf.float32, name=None)
tf.ones_like(tensor, dtype=None, name=None)
序列
tf.range(start, limit, delta=1, name='range')
tf.linspace(start, stop, num, name=None)
③随机数
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)tf.random_uniform(shape, minval=0.0, maxval=1.0, dtype=tf.float32, seed=None, name=None)
tf.random_shuffle(value, seed=None, name=None) # value is a list tf.Variable(initial_value=None, name=None, shape=None, dtype=None [,……])
Variable变量只能用上述的类型来初始化,或者简单的初始化为一个数0。用处有weights biaes globa_step这些在训练中变动的量。
#
x = tf.constant( [1,2,3,4,5]) #定义了一个向量
x = tf.constant( -1.0,shape=(2,3),dtype=float16) # shape(2,3)全用-1.0填充
import tensorflow as tf
tensor1 = tf.linspace(1.0, 10.0, 7, name="linspace")
tensor2 = tf.Variable(tf.random_uniform([2, 3], minval=0.0, maxval=2.0, dtype=tf.float32, seed=1234, name="v8_1"))
sess = tf.Session()
with sess.as_default():
print('tensor1 is :', tensor1.eval())
sess.run(tf.global_variables_initializer()) # 所有变量的赋值和计算都需要sess.run()完成,此处是所有变量集体初始化
result = sess.run(tensor2)
print(type(result), '\n', result)
2、tf矩阵切片与连接
tf.slice(input_, begin, size, name=None) # 重要的两个参数 起始位置和大小
tf.concat([a, b], axis=0)
# test of tf.slice
import tensorflow as tf
tensor1 = tf.Variable(tf.truncated_normal(shape=[3, 5], dtype=tf.float32))
tensor2 = tf.slice(tensor1, [1, 2], [2, 3])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print('tensor1 is :\n', sess.run(tensor1))
result = sess.run(tensor2)
print(type(result), '\n', result)
# test of tf.concat
import tensorflow as tf
tf.InteractiveSession()
a = tf.Variable(tf.random_normal(shape=[2, 2], dtype=tf.float32))
b = tf.Variable(tf.random_normal(shape=[2, 2], dtype=tf.float32))
c1 = tf.concat([a, b], axis=0)
tf.global_variables_initializer().run()
print(c1.eval())
3、矢量运算
关于运算都需要sess.run()输出结果,以下x y的数据类型可以是list ndarray tf数据
①一元函数 点击查看
tf.sin(x)、tf.cos(x)、tf.tan(x)、tf.asin(x)、tf.acos(x)、tf.atan(x)
tf.negative(x)、tf.reciprocal(x)、tf.abs(x)、tf.round(x)、tf.ceil(x)、tf.floor(x) # 负数 导数
tf.sqrt(x)、tf.exp(x)、tf.log(x)
②二元函数
tf.add(x,y)、tf.subtract(x,y)、tf.multiply(x,y)、tf.divide(x,y)、tf.mod(x,y)、tf.mod(x,y)
import tensorflow as tf
with tf.device('/cpu:0'):
a = tf.constant(8.0, shape=(3,))
b = tf.placeholder(tf.float32, shape=(3,))
c = tf.divide(a, b)
d = tf.truediv(a, b)
e = tf.div(a, b)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
c, d, e = sess.run([c, d, e], feed_dict={b: [3, 5, 7]}) # feed_dict = {b : np.array([3,5,7]) }
print(c, d, e, sep='\n')
tf.placeholder(tf.float32,shape(3,))占位符作为整个计算图的输入部分,在sess.run时用feed_dict填入真实数据。
tf.Variable具有占位符功能,但缺少shape这个变量就不太好用了!
import tensorflow as tf
import numpy as np
x = tf.Variable(tf.constant(0, shape=(2, 3)))
y = tf.round(x)
data = np.random.uniform(-10, 10, 6).reshape(2, 3)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
res = sess.run(y, feed_dict={x: data})
print(type(res), ':\n', res)
print('the numpy data is:\n', data)
Variable的占位符功能
③矩阵运算
tf.matual(a,b, transpose_a=False,transpose_b=False,adjoint_a=False,adjoint_b=False,name=None)
tf.transpose(input,perm) # 维度转换 perm=[1,0]用以矩阵轴变换
) # 方阵行列式的值
tf.matrix_inverse(x) # 方阵的逆
tf.svd(x) # 奇异值分解
tf.qr(x) # QR分解
tf.norm(x) # 求张量范数
4、axis :reduce various dimensions of a tensor
None, keep_dims=False, name=None)
tf.reduce_mean(x,axes) # keep_dims name
tf.reduce_max(x,axes)
tf.reduce_min(x,axes)
tf.reduce_all(x,axes) # 在指定维度上的逻辑与
tf.reduce_any(x,axes) # 在制定维度上的逻辑或
tf.reduce_prod(x,axes) # 返回一个单一的值 所有元素的乘积
----------------------------------------------------------- 以上和numpy的都相同
tf.accumulate_n([x,y,z……]) # add只能tf.(x,y)对两个tensor运算,accumulate_n相当于扩展了add的功能
tf.count_nonzero(x)
⑤索引提取
# x if condition else y, condition。 condition为bool类型的 可用tf.equal()或[False, True, False]
tf.where(condition, x=None, y=None, name=None) # 对应之前版本的tf.select;下面例子中试试tf.where(True,tensor1,tensor2),返回[1,7,9]
tf.argmax(x, axes=None, name=None, output_type=tf.int64) # 返回沿着坐标轴方向的最大/最小值的索引
tf.argmin(x, axes=None, name=None, output_type=tf.int64)
import tensorflow as tf
import numpy as np
tensor1 = tf.constant([1, 7, 9])
tensor2 = tf.constant([32, 54, 87])
tensor3 = tf.where(np.array([False, True, False]), tensor1, tensor2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
result = sess.run(tensor3)
print(result)
2021-08-28 20:17:34