zoukankan      html  css  js  c++  java
  • TensorFlow2_200729系列---20、自定义层

    TensorFlow2_200729系列---20、自定义层

    一、总结

    一句话总结:

    继承layers.Layer,初始化方法中可以定义变量,call方法中可以实现神经网络矩阵乘法
    # 自定义层(比如之前的全连接dense层)
    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 

    1、自定义神经网络model?

    继承keras.Model就好,模型的那些方法都会继承过来,初始化方法和call方法中实现自己的初始化和逻辑
    # 自定义model
    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

    二、自定义层

    博客对应课程的视频位置:

    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()
    
    # 自定义层(比如之前的全连接dense层)
    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 
    
    # 自定义model
    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.summary()
    
    
    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)
    
    datasets: (60000, 28, 28) (60000,) 0 255
    Epoch 1/5
    469/469 [==============================] - 2s 4ms/step - loss: 0.2862 - accuracy: 0.9138
    Epoch 2/5
    469/469 [==============================] - 3s 6ms/step - loss: 0.1335 - accuracy: 0.9623 - val_loss: 0.1319 - val_accuracy: 0.9635
    Epoch 3/5
    469/469 [==============================] - 2s 4ms/step - loss: 0.1066 - accuracy: 0.9702
    Epoch 4/5
    469/469 [==============================] - 3s 6ms/step - loss: 0.0926 - accuracy: 0.9746 - val_loss: 0.1499 - val_accuracy: 0.9664
    Epoch 5/5
    469/469 [==============================] - 2s 4ms/step - loss: 0.0865 - accuracy: 0.9773
    Model: "my_model_3"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    my_dense_15 (MyDense)        multiple                  200960    
    _________________________________________________________________
    my_dense_16 (MyDense)        multiple                  32896     
    _________________________________________________________________
    my_dense_17 (MyDense)        multiple                  8256      
    _________________________________________________________________
    my_dense_18 (MyDense)        multiple                  2080      
    _________________________________________________________________
    my_dense_19 (MyDense)        multiple                  330       
    =================================================================
    Total params: 244,522
    Trainable params: 244,522
    Non-trainable params: 0
    _________________________________________________________________
    79/79 [==============================] - 1s 8ms/step - loss: 0.1212 - accuracy: 0.9692
    tf.Tensor(
    [7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1 3 1 3 4 7 2 7
     1 2 1 1 7 4 2 3 5 1 2 4 4 6 3 5 5 6 0 4 1 9 5 7 8 9 3 7 9 6 4 3 0 7 0 2 9
     1 7 3 2 9 7 7 6 2 7 8 4 7 3 6 1 3 6 9 3 1 4 1 7 6 9 6 0 5 4 9 9 2 1 9 4 8
     7 3 9 7 9 4 4 9 2 5 4 7 6 7 9 0 5], shape=(128,), dtype=int64)
    tf.Tensor(
    [7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1 3 1 3 4 7 2 7
     1 2 1 1 7 4 2 3 5 1 2 4 4 6 3 5 5 6 0 4 1 9 5 7 8 9 3 7 4 6 4 3 0 7 0 2 9
     1 7 3 2 9 7 7 6 2 7 8 4 7 3 6 1 3 6 9 3 1 4 1 7 6 9 6 0 5 4 9 9 2 1 9 4 8
     7 3 9 7 4 4 4 9 2 5 4 7 6 7 9 0 5], shape=(128,), dtype=int64)
    
    In [ ]:
     
     
    我的旨在学过的东西不再忘记(主要使用艾宾浩斯遗忘曲线算法及其它智能学习复习算法)的偏公益性质的完全免费的编程视频学习网站: fanrenyi.com;有各种前端、后端、算法、大数据、人工智能等课程。
    博主25岁,前端后端算法大数据人工智能都有兴趣。
    大家有啥都可以加博主联系方式(qq404006308,微信fan404006308)互相交流。工作、生活、心境,可以互相启迪。
    聊技术,交朋友,修心境,qq404006308,微信fan404006308
    26岁,真心找女朋友,非诚勿扰,微信fan404006308,qq404006308
    人工智能群:939687837

    作者相关推荐

  • 相关阅读:
    Nginx+tomcat负载均衡配置
    详解HttpURLConnection
    tomcat配置文件之Server.xml
    Android ADB命令大全(通过ADB命令查看wifi密码、MAC地址、设备信息、操作文件、查看文件、日志信息、卸载、启动和安装APK等)
    Tomcat多站点部署方式
    跨域、跨服务器调用时候session丢失的问题
    Linux系统的命令别名功能
    CentOS 升级GCC G++
    npm 安装碰到SSL问题
    centos图形界面的开启和关闭
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/13443970.html
Copyright © 2011-2022 走看看