Skip to content
This repository has been archived by the owner on Sep 5, 2021. It is now read-only.

Latest commit

 

History

History
174 lines (120 loc) · 2.21 KB

23-Day5.md

File metadata and controls

174 lines (120 loc) · 2.21 KB

WW5课程小结

2021.3.23

回顾

自动微分

AD

保存较少的中间变量

张量表示神经网络

Tensor N维数组

Softmax

def softmax(x):
    s=0
    for i in x:
        s+=np.exp(i)
    return np.array(np.exp(x)/s)

TensorFlow

import tensorflow as tf

tensor张量

实质是具有统一类型的N维数组

张量创建

tf.constant(
    value,
    dtype=None,
    shape=None, 
    name='Const',
    verify_shape=False
)

0,1,2,3维张量

r0_tensor=tf.constant(4)
r1_tensor=tf.constant([2.,3.,4.])
r2_tensor=tf.constant([[2.,3.,4.],
                       [5,6,7]],dtype=tf.float16)		

shape(3,2,4,5)从大到小分区定义

Tensor运算

张量转换为numpy数组

r2_tensor.numpy() #以numpy形式调用
np.array(r2_tensor) #创建numpy数组

四则运算

tf.add()
a+b
tf.multiply()
a*b
tf.matmul()
a @ b

张量运算符运算(op)

执行张量数据类型转换

tf.cast(x,dtype,name=None)
tf.cast(r1_tensor,dtype=	tf.uint8)

Tensor reshape

Tensor 索引

遵循标准Python索引

  • 从0开始
  • -1,-2倒序
  • 冒号用于切片 start:step:stop
  • 左闭右开

单轴

r3_tensor[::-1].numpy()

多轴切片

r2_tensor[1,1]
>>> 6
r2_tensor[:,1]
r2_tensor[:,1:]
>>> [[3,4],[6,7]]

特殊张量表示

tf.Tensor(b'Gray wolf',shape=(),dtype=string) #字符串张量

字符串张量

稀疏张量

TensorFlow变量

a=tf.Variable([2.0,3.0])
a.shape
a.dtype
a.numpy()
a.trainable() #bool 自动微分
tf.Variable([5,6]) #可以是常量、变量或numpy

变量的值可以通过assign函数更改

自动微分

autodiff

梯度带

持久梯度带

记录控制流

#example
import tensorflow as tf 
x=tf.constant(1.0)
with tf.GradientTape() as t:
    t.watch(x)
    y=x*x+tf.exp(x)
dy_dx=t.gradient(y,x)
del t

dy_dx.numpy()
>>> 4.7182817

进行高阶导数求导

d2y_dx2=t.gradient(dy_dx,x)