张量运算
导入库,并检查版本
import tensorflow as tf
print(tf.executing_eagerly())
print(tf.__version__)import numpy as np
True
2.0.0
执行一些操作
加法
a = tf.constant([-1,1,2])
b = tf.constant([3,4,5])
tf.add(a,b)
<tf.Tensor: id=2, shape=(3,), dtype=int32, numpy=array([2, 5, 7])>
次方
tf.pow(a,2)
tf.pow(a,b)
tf.exp(1.0)
tf.math.log(tf.exp(1.0))
广播机制
a1 = tf.constant(np.arange(12).reshape(4,3))
a+a1
点乘叉乘
tf.multiply(a,b)
c = tf.constant(np.arange(6),shape=(2,3))
d = tf.constant(np.arange(6),shape=(3,2))
tf.matmul(c,d)
堆叠
ab_stack = tf.stack(values=(a,b),axis=0)
tf.reduce_sum(ab_stack,axis=0)
tf.reduce_max(ab_stack)
tf.argmax(ab_stack,axis=1)
tf.argsort(ab_stack,axis=1)
数值类型转换
b = tf.cast(a,dtype=tf.float32)
a1 = tf.constant([-1,0,3])
b1= tf.cast(a1,tf.bool)
numpy和tf类型转换
na = np.arange(12).reshape(3,4)
ta= tf.convert_to_tensor(na)
na1 = ta.numpy()
isinstance(ta,tf.Tensor)
生成全0或全1数组
tf.zeros(shape=[2,2],dtype=tf.float32)
tf.fill([2,2],99)
生成、打乱随机数组
tf.random.normal(shape=(2,2))
tf.random.set_seed(8)
tf.random.normal([2,2])
shuffle1 = tf.random.uniform(shape=[2,2,2],minval=1,maxval=11,dtype=tf.float32)
tf.random.shuffle(shuffle1)