MOOC北大tensorflow笔记一

青旅半醒 2021-09-25 12:58 465阅读 0赞

一.张量

·张量tensor :多维数组(列表) 阶:张量的维数

·张量可以表示0阶到n阶数组(列表)

张量的数据类型:

20210804162039906.png

代码清单:

  1. import tensorflow as tf
  2. import numpy as np
  3. a=tf.constant([[2,3],[2,5]],dtype=tf.int32)
  4. print(a)
  5. print(a.dtype)
  6. print(a.shape)
  7. b=tf.constant(np.arange(12).reshape((3,4)),dtype=tf.float32)
  8. print(b)
  9. print(b.dtype)
  10. print(b.shape)
  11. # 用正态分布生成数据
  12. c=tf.random.normal([2,2],mean=0.5,stddev=1)#生成均值为0.5,标准差为1的二维数据
  13. d=tf.random.truncated_normal([2,2],mean=0.5,stddev=1)#生成均值为0.5,标准差为1的二维数据,这些元素在两倍标准差之内,数据更向均值0.5集中
  14. e=tf.random.uniform([2,2],minval=12,maxval=20)# 生成均匀分布随机数[minval,maxval)
  15. print(e)
  16. # 强制tensor转换为该数据类型
  17. f=tf.cast(b,tf.int32)
  18. print(f)
  19. #计算张量维度上的最大值,最小值,均值等等
  20. print(tf.reduce_max(b))
  21. ======================================打印结果===========================================
  22. tf.Tensor(
  23. [[2 3]
  24. [2 5]], shape=(2, 2), dtype=int32)
  25. <dtype: 'int32'>
  26. (2, 2)
  27. tf.Tensor(
  28. [[ 0. 1. 2. 3.]
  29. [ 4. 5. 6. 7.]
  30. [ 8. 9. 10. 11.]], shape=(3, 4), dtype=float32)
  31. <dtype: 'float32'>
  32. (3, 4)
  33. tf.Tensor(
  34. [[18.466003 13.447195]
  35. [18.900255 17.91539 ]], shape=(2, 2), dtype=float32)
  36. tf.Tensor(
  37. [[ 0 1 2 3]
  38. [ 4 5 6 7]
  39. [ 8 9 10 11]], shape=(3, 4), dtype=int32)
  40. tf.Tensor(11.0, shape=(), dtype=float32)

二. tf.Variable

将变量标记为“可训练”,被标记的变量会在方向传播中记录梯度信息。神经网络训练中,常用该函数标记带训练参数。

tf.Variable(初始值)

  1. w = tf.Variable(tf.constant(5, dtype=tf.float32))#定义随机参数值为5,设定为可训练

这样就可以在梯度下降中更新参数w

三. 常用函数对应的

1.四则运算

2021080417095087.png

注意:只有维度相同的张量才能进行四则运算

2.n次方

20210804171148379.png

3.矩阵相乘 tf.matmul(矩阵1,矩阵2)

4.tf.data.Dataset.from_tensor_slices

切分传入张量的第一维度,生成输入特征标签对,构建数据集

tf.data.Dataset.from_tensor_slices((输入特征,标签))

代码清单:

  1. # 标签配对
  2. features=tf.constant([12,34,45,37])
  3. labels=tf.constant(['a','b','c','d'])
  4. dataset=tf.data.Dataset.from_tensor_slices((features,labels))
  5. print(dataset)
  6. for el in dataset:
  7. print(el)
  8. =============打印结果=======================================
  9. <TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.string)>
  10. (<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=string, numpy=b'a'>)
  11. (<tf.Tensor: shape=(), dtype=int32, numpy=34>, <tf.Tensor: shape=(), dtype=string, numpy=b'b'>)
  12. (<tf.Tensor: shape=(), dtype=int32, numpy=45>, <tf.Tensor: shape=(), dtype=string, numpy=b'c'>)
  13. (<tf.Tensor: shape=(), dtype=int32, numpy=37>, <tf.Tensor: shape=(), dtype=string, numpy=b'd'>)

Numpy和Tensor格式都可用改语句读入数据

5.tf.GradientTape()

GradientTape是eager模式下计算梯度用的

  1. with tf.GradientTape() as tape:
  2. w = tf.Variable(tf.constant(3.0))
  3. loss=tf.pow(w,2)
  4. grad=tape.gradient(loss,w)
  5. print(grad)
  6. ==============计算结果==================
  7. tf.Tensor(6.0, shape=(), dtype=float32)

with as结构来计算梯度过程,将tf.GradientTape()的返回值记录到tape中,在定义代价函数loss,下面tape.gradinet(代价函数,对谁求偏导)来计算求偏导结果。如上例子结果为6

6.enumerate

enumerate是python的内建函数,它可以遍历每个元素(如列表、元组、字符串),组合为:索引 元素,常在for循环中使用。

enumerate(列表名)

  1. seq=['one','two','three']
  2. for i ,el in enumerate(seq):
  3. print(i,el)
  4. =========运行结果==============
  5. 0 one
  6. 1 two
  7. 2 three

7.tf.one_hot()

独热编码(one-hot encoding):在分类问题中,常用独热码做标签,标记类别:1表示是,0表示非。函数将待转换的数据,转为one-hot形式的数据输出。

tf.one_hot(带转换数据,depth=几分类)

  1. classes=4
  2. labels=tf.constant([1,3,0])
  3. output=tf.one_hot(labels,depth=classes)
  4. print(output)
  5. ===============运行结果=====================
  6. tf.Tensor(
  7. [[0. 1. 0. 0.]
  8. [0. 0. 0. 1.]
  9. [1. 0. 0. 0.]], shape=(3, 4), dtype=float32)

如上例子:分为四分类,数据标签有3个数字,对应位置填1就好,比如,第二个数据3,在下面第二行索引为3处。

8.tf.nn.soft.max()

当n分类的n个输出(y0,y1,…….yn-1)通过softmax()函数,使符合概率分布。每个概率值为0~1之间,这些概率的和为1。例如下图鸢尾花的例子。

  1. ![20210804215318163.png][]

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxOTUwNDQ3_size_16_color_FFFFFF_t_70

用代码实现算法过程:

如果神经网络前向传播结果为[1.01,2.01,-0.66],送入算法中,得出概率分布结果。

  1. y=tf.constant([1.01,2.01,-0.66])
  2. y_pro=tf.nn.softmax(y)
  3. print("After softmax y_pro is:",y_pro)
  4. =================运行结果================
  5. After softmax y_pro is: tf.Tensor([0.25598174 0.69583046 0.04818781], shape=(3,), dtype=float32)

9.assign_sub

自减,赋值操作,更新参数的值并返回,注意的是条用assign_sub之前,先用tf.Variable定义变量w为可训练(可自更新)

w.assign_sub(w要自减的内容)

  1. w=tf.Variable(4) # 定义可训练的值
  2. w.assign_sub(1) # w进行自减1
  3. print(w)
  4. ==============运行结果=============
  5. <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>

10.tf.argmax

返回张量沿指定的维度最大值的索引

tf.argmax(张量名,axis=操作轴) axis=0纵向 axis=1横向

  1. test=np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
  2. print(test)
  3. print(tf.argmax(test,axis=1))#横向每行最大值的索引号
  4. print(tf.argmax(test,axis=0))#纵向每列最大值的索引号
  5. ===========运行结果======================
  6. [[1 2 3]
  7. [2 3 4]
  8. [3 4 5]
  9. [4 5 6]]
  10. tf.Tensor([2 2 2 2], shape=(4,), dtype=int64)
  11. tf.Tensor([3 3 3], shape=(3,), dtype=int64)

发表评论

表情:
评论列表 (有 0 条评论,465人围观)

还没有评论,来说两句吧...

相关阅读

    相关 生信笔记-mooc【武大】

    .DNA拓扑学 在拓扑结构的限制下,DNA进行复制等过程。还有连环数=扭转数+缠绕数。 2.拓扑异构酶 DNA变性破坏了两条链之间碱基形成的氢键。和拓扑异构酶是不同的。