MOOC北大tensorflow笔记一
一.张量
·张量tensor :多维数组(列表) 阶:张量的维数
·张量可以表示0阶到n阶数组(列表)
张量的数据类型:
代码清单:
import tensorflow as tf
import numpy as np
a=tf.constant([[2,3],[2,5]],dtype=tf.int32)
print(a)
print(a.dtype)
print(a.shape)
b=tf.constant(np.arange(12).reshape((3,4)),dtype=tf.float32)
print(b)
print(b.dtype)
print(b.shape)
# 用正态分布生成数据
c=tf.random.normal([2,2],mean=0.5,stddev=1)#生成均值为0.5,标准差为1的二维数据
d=tf.random.truncated_normal([2,2],mean=0.5,stddev=1)#生成均值为0.5,标准差为1的二维数据,这些元素在两倍标准差之内,数据更向均值0.5集中
e=tf.random.uniform([2,2],minval=12,maxval=20)# 生成均匀分布随机数[minval,maxval)
print(e)
# 强制tensor转换为该数据类型
f=tf.cast(b,tf.int32)
print(f)
#计算张量维度上的最大值,最小值,均值等等
print(tf.reduce_max(b))
======================================打印结果===========================================
tf.Tensor(
[[2 3]
[2 5]], shape=(2, 2), dtype=int32)
<dtype: 'int32'>
(2, 2)
tf.Tensor(
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]], shape=(3, 4), dtype=float32)
<dtype: 'float32'>
(3, 4)
tf.Tensor(
[[18.466003 13.447195]
[18.900255 17.91539 ]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]], shape=(3, 4), dtype=int32)
tf.Tensor(11.0, shape=(), dtype=float32)
二. tf.Variable
将变量标记为“可训练”,被标记的变量会在方向传播中记录梯度信息。神经网络训练中,常用该函数标记带训练参数。
tf.Variable(初始值)
w = tf.Variable(tf.constant(5, dtype=tf.float32))#定义随机参数值为5,设定为可训练
这样就可以在梯度下降中更新参数w
三. 常用函数对应的
1.四则运算
注意:只有维度相同的张量才能进行四则运算
2.n次方
3.矩阵相乘 tf.matmul(矩阵1,矩阵2)
4.tf.data.Dataset.from_tensor_slices
切分传入张量的第一维度,生成输入特征标签对,构建数据集
tf.data.Dataset.from_tensor_slices((输入特征,标签))
代码清单:
# 标签配对
features=tf.constant([12,34,45,37])
labels=tf.constant(['a','b','c','d'])
dataset=tf.data.Dataset.from_tensor_slices((features,labels))
print(dataset)
for el in dataset:
print(el)
=============打印结果=======================================
<TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.string)>
(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=string, numpy=b'a'>)
(<tf.Tensor: shape=(), dtype=int32, numpy=34>, <tf.Tensor: shape=(), dtype=string, numpy=b'b'>)
(<tf.Tensor: shape=(), dtype=int32, numpy=45>, <tf.Tensor: shape=(), dtype=string, numpy=b'c'>)
(<tf.Tensor: shape=(), dtype=int32, numpy=37>, <tf.Tensor: shape=(), dtype=string, numpy=b'd'>)
Numpy和Tensor格式都可用改语句读入数据
5.tf.GradientTape()
GradientTape是eager模式下计算梯度用的
with tf.GradientTape() as tape:
w = tf.Variable(tf.constant(3.0))
loss=tf.pow(w,2)
grad=tape.gradient(loss,w)
print(grad)
==============计算结果==================
tf.Tensor(6.0, shape=(), dtype=float32)
with as结构来计算梯度过程,将tf.GradientTape()的返回值记录到tape中,在定义代价函数loss,下面tape.gradinet(代价函数,对谁求偏导)来计算求偏导结果。如上例子结果为6
6.enumerate
enumerate是python的内建函数,它可以遍历每个元素(如列表、元组、字符串),组合为:索引 元素,常在for循环中使用。
enumerate(列表名)
seq=['one','two','three']
for i ,el in enumerate(seq):
print(i,el)
=========运行结果==============
0 one
1 two
2 three
7.tf.one_hot()
独热编码(one-hot encoding):在分类问题中,常用独热码做标签,标记类别:1表示是,0表示非。函数将待转换的数据,转为one-hot形式的数据输出。
tf.one_hot(带转换数据,depth=几分类)
classes=4
labels=tf.constant([1,3,0])
output=tf.one_hot(labels,depth=classes)
print(output)
===============运行结果=====================
tf.Tensor(
[[0. 1. 0. 0.]
[0. 0. 0. 1.]
[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。例如下图鸢尾花的例子。
![20210804215318163.png][]
用代码实现算法过程:
如果神经网络前向传播结果为[1.01,2.01,-0.66],送入算法中,得出概率分布结果。
y=tf.constant([1.01,2.01,-0.66])
y_pro=tf.nn.softmax(y)
print("After softmax y_pro is:",y_pro)
=================运行结果================
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要自减的内容)
w=tf.Variable(4) # 定义可训练的值
w.assign_sub(1) # w进行自减1
print(w)
==============运行结果=============
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
10.tf.argmax
返回张量沿指定的维度最大值的索引
tf.argmax(张量名,axis=操作轴) axis=0纵向 axis=1横向
test=np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
print(test)
print(tf.argmax(test,axis=1))#横向每行最大值的索引号
print(tf.argmax(test,axis=0))#纵向每列最大值的索引号
===========运行结果======================
[[1 2 3]
[2 3 4]
[3 4 5]
[4 5 6]]
tf.Tensor([2 2 2 2], shape=(4,), dtype=int64)
tf.Tensor([3 3 3], shape=(3,), dtype=int64)
还没有评论,来说两句吧...