tensorflow2.0张量运算

张量运算

导入库,并检查版本

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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值