TensorFlow07 神经网络-自定义网络

发布时间 2023-06-19 20:38:31作者: 哎呦哎(iui)

▪ keras.Sequential
▪ keras.layers.Layer
▪ keras.Model

1 keras.Sequential

image
这样就完成了五层的神经网络的一个搭建,然后我们在activation中也可以指定每一层的激活函数

2 model.trainable_variables

▪ model.trainable_variables
▪ model.call()

model.trainable_variables
我们之前做的时候,都是定义一个variable类型的w1,w2,--b1,b2,但是现在我们都是用Sequential来定义的这个神经网络,但是后面求梯度的时候我们需要用到这些值,所以我们后面求梯度的时候我们可以用这个grads = tape.gradient(loss_ce, model.trainable_variables)

3 Layer/Model

▪ Inherit from keras.layers.Layer/keras.Model
▪ __ init__
▪ call
▪ Model: compile/fit/evaluate/predict
其中这个__ init__和call()方法是layer.Layer所必须实现的。

所以我们在使用这个这些方法的时候我们必须继承自keras.model。

4 具体实现

之前如果是layers.Dense(512),之后再build([none,784]),之后我们的这个w就是:[784,512]。
b就是一个[512]。
image

其中这个self.kernel和self.bias是通过add.variable来创建的,并不是通过tf.constant()。然后这个里面的名字'w','b'是可以换名字的,尽量取一个有意义的名字。
image
其中这两个部分都是自己写的。

然后这个层就创建完了,我们如果需要通过这个定义的层来定义一个神经网络的话。
image
然后这个是自定义网络层的代码:

import  tensorflow as tf
from    tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
from 	tensorflow import keras

def preprocess(x, y):
    """
    x is a simple image, not a batch
    """
    x = tf.cast(x, dtype=tf.float32) / 255.
    x = tf.reshape(x, [28*28])
    y = tf.cast(y, dtype=tf.int32)
    y = tf.one_hot(y, depth=10)
    return x,y


batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max())



db = tf.data.Dataset.from_tensor_slices((x,y))
db = db.map(preprocess).shuffle(60000).batch(batchsz)
ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz) 

sample = next(iter(db))
print(sample[0].shape, sample[1].shape)


network = Sequential([layers.Dense(256, activation='relu'),
                     layers.Dense(128, activation='relu'),
                     layers.Dense(64, activation='relu'),
                     layers.Dense(32, activation='relu'),
                     layers.Dense(10)])
network.build(input_shape=(None, 28*28))
network.summary()


class MyDense(layers.Layer):

	def __init__(self, inp_dim, outp_dim):
		super(MyDense, self).__init__()

		self.kernel = self.add_weight('w', [inp_dim, outp_dim])
		self.bias = self.add_weight('b', [outp_dim])

	def call(self, inputs, training=None):

		out = inputs @ self.kernel + self.bias

		return out 

class MyModel(keras.Model):

	def __init__(self):
		super(MyModel, self).__init__()

		self.fc1 = MyDense(28*28, 256)
		self.fc2 = MyDense(256, 128)
		self.fc3 = MyDense(128, 64)
		self.fc4 = MyDense(64, 32)
		self.fc5 = MyDense(32, 10)

	def call(self, inputs, training=None):

		x = self.fc1(inputs)
		x = tf.nn.relu(x)
		x = self.fc2(x)
		x = tf.nn.relu(x)
		x = self.fc3(x)
		x = tf.nn.relu(x)
		x = self.fc4(x)
		x = tf.nn.relu(x)
		x = self.fc5(x) 

		return x


network = MyModel()


network.compile(optimizer=optimizers.Adam(lr=0.01),
		loss=tf.losses.CategoricalCrossentropy(from_logits=True),
		metrics=['accuracy']
	)

network.fit(db, epochs=5, validation_data=ds_val,
              validation_freq=2)
 
network.evaluate(ds_val)

sample = next(iter(ds_val))
x = sample[0]
y = sample[1] # one-hot
pred = network.predict(x) # [b, 10]
# convert back to number 
y = tf.argmax(y, axis=1)
pred = tf.argmax(pred, axis=1)

print(pred)
print(y)