TensorFlow05-全连接层

发布时间 2023-06-17 15:14:52作者: 哎呦哎(iui)

▪ Matmul
▪ Neural Network
▪ Deep Learning
▪ Multi-Layer

1.Matmul

  • out=f(x@w+b)
  • out=relu(x@w+b)
    image
    我们只看第一位h00,h10,其中image
    类似于一个激活函数(relu函数)
    image
    image
    image
    在一层中我们包括这一层的权值和偏置在里面的。
    image
    Here comes Deep Learning:
    image
    在以前不叫作Deep Learning 叫做神经网络。
    现在的Deep Learning 都是成百上千层。
    image

2 Fully connected layer(全连接层)

主要实现:

tf.keras.layers.Dense(x)

例如:

x=tf.random.normal([4,784])
net=tf.keras.layers.Dense(512)
out=net(x)
#这个net(x),就是把它变成[4,512]类似于一个降维的效果

out.shape
#TensorShape([4, 512])

net.kernel.shape , net.bias.shape
#(TensorShape([784, 512]), TensorShape([512]))
#这个net.kernel就是w(权值),net.bias就是b(偏置)

image
这里我们可以不用创建w和b的,就是如果没有的话,它自动创建。
image
我们也可以手动创建,但是我们一般都是只创建一次。
下面的例子就是如果我们build的和传入的不相同的例子:
image
为什么叫全连接层呢?
因为它每一层都和下一层相互连接。
怎么创建多个全连接层呢?

3 Multi-Layers(创建多个全连接层)

keras.Sequential([layer1,layer2,layer3])

image
举个例子:

import tensorflow as tf
from tensorflow import keras
x=tf.random.normal([2,3])
model=keras.Sequential([
    keras.layers.Dense( 2, activation='relu'),
    keras.layers.Dense( 2 , activation='relu'),
    keras.layers.Dense( 2 )
])
#上面的是定义一个全连接层

model.build(input_shape=[None,3])#或者model.build(x)
#用这个全连接层进行训练

model.summary()
#展示他的每一层的蚕食信息

for p in model.trainable_variables:
    print(p.name,p.shape)
#展示它的每一次的w和b

image
image