您当前的位置: 首页 >  人工智能

暂无认证

  • 0浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

人工智能|Tensorflow-2.0学习笔记:基础操作篇一

发布时间:2019-10-10 00:07:00 ,浏览量:0

欢迎点击「算法与编程之美」↑关注我们!

本文首发于微信公众号:"算法与编程之美",欢迎关注,及时了解更多此系列文章。

数据类型与tensor创建

一、数据类型

  1. 1.  TF中的数据表达

tensor是tensorflow上数据的载体

   what's Tensor

       标量    scalar : 1.1   

       向量    vector :[1.1],[1.1,2.2,...]

       矩阵    matrix :[[0.7,1.5],[2.1,3],[5,6]]

       维度大于2的矩阵   tensor : rank>2

    从工程上来讲所有数据都可以叫做tensor

2.TF中的数据类型

   int,float,double

   bool

string

创建一个常量or创建一个标量tensor

a=tf.constant(1)#默认为32位b=tf.constant(2.,dtype=tf.double)#创建浮点型tensor,并指定为双精度c=tf.constant([True,False])#创建布尔型d=tf.constant('hello,word')#创建字符串型

tensor常用属性

指定tensor在哪个设备上运行,gpu or cpu

with tf.device("cpu"):

查看tensor在哪个设备上运行

a.device

tensor的运行设备转移

aa=a.gpu()

将tensor转换成numpy

b.numpy()

查看维度

b.ndim#返回维度tf.rank(b)#或者这个,还能查看shape和dtypeb.shape()#与python中的shape功能相似

       判断某个数据是不是tensor,以下两种方式

isinstance(a,tf.Tensor)

数据类型转换

#查看数据类型a.dtype,b.dtype#判断数据类型a.dtype=tf.float32#数据类型转换a=np.arange(5)#numpy生成的数据都默认为64位aa=tf.convert_to_tensor(a)#转换为tensoraa=tf.convert_to_tensor(a,dtype=tf.int32)#转换为tensor,并改为32位tf.cast(aa,dtype=tf.float32)#将aa转换为浮点型32位b=tf.constant([0,1])#整型0、1可以和布尔类型相互转换

Variable 变量,可更改优化的数据。在tensorflow中Variable自带可求导特性

a=tf.range(5)#isinstance存在一些问题,一般建议用tf.is_tensorisinstance(b,tf.Tensor)#Falsetf.is_tensor(b)#True返回tensor中的具体数据a.numpy()

二、创建tensor

1.formnumpy,list   从numpy和python的list中经转换得到

2.zeros,ones       np.zeros、np.ones,tf.zeros、tf.ones

3.fill              随意用某个数填充

4.random          随机化的初始化

5.constant         标量

6.Application  

#直接用List,要求list中的数据都可以转换为可计算的数据tf.convert_to_tensor([1,2])#ones,zeros接受的数据是shape,[2,3]指生成二行三列的矩阵tf.convert_to_tensor(np.ones[2,3])#与上方功能相同tf.ones([2,3])#生成与a的shape相同的全0矩阵#等同于tf.zeros(a.shape)#生成2行2列的tensor,并用9填充

Random初始化

#正态分布初始化tf.random.normal([2,2],mean=1,stddey=1)#生成2行2列的tensor,其中的每个值都通过正态分布得出#mean是均值、stddey是方差。不填默认0、1,标准正态分布#截断正态分布,去除正态分布中左右两侧较少的分布区域值,一般来说比直接的正态分布好tf.random.truncated_normal([2,2],mean=0,stddey=1)#均匀分布tf.random.uniform([2,2],minval=0,maxval=1)#从0到1之间均匀采样

随机打散

假设现在a中有48张照片,28*28,3通道的,用tensor表示为[48,28,28,3].。现在要将这些照片顺序打散。

index=tf.range(48)#生成对应索引,每个索引对应一张照片idx=tf.random.shuffle(index)#将index随机打乱,但是图片的顺序还没发生变化a=tf.gather(a,index)#用gather函数可以让照片与被打乱的index一一对应,这样就实现了随机打散

END

主  编   |   张祯悦

责  编   |   马原涛

 where2go 团队

   

微信号:算法与编程之美          

640?wx_fmt=jpeg

长按识别二维码关注我们!

温馨提示:点击页面右下角“写留言”发表评论,期待您的参与!期待您的转发!

关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.3558s