TensorFlow keras卷积神经网络 添加L2正则化

model = keras.models.Sequential([
        #卷积层1
        keras.layers.Conv2D(32,kernel_size=5,strides=1,padding="same",data_format="channels_last",activation=tf.nn.relu,kernel_regularizer=keras.regularizers.l2(0.01)),
        #池化层1
        keras.layers.MaxPool2D(pool_size=2,strides=2,padding="same"),
        #卷积层2
        keras.layers.Conv2D(64,kernel_size=5,strides=1,padding="same",data_format="channels_last",activation=tf.nn.relu),
        #池化层2
        keras.layers.MaxPool2D(pool_size=2,strides=2,padding="same"),
        #数据整理
        keras.layers.Flatten(),
        #1024个,全连接层
        keras.layers.Dense(1024,activation=tf.nn.relu),
        #100个,全连接层
        keras.layers.Dense(100,activation=tf.nn.softmax)
    ])

  

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

from tensorflow.python.keras.datasets import cifar100
from tensorflow.python import keras
import tensorflow as tf


class CNNMnist(object):

    model = keras.models.Sequential([
        #卷积层1
        keras.layers.Conv2D(32,kernel_size=5,strides=1,padding="same",data_format="channels_last",activation=tf.nn.relu,kernel_regularizer=keras.regularizers.l2(0.01)),
        #池化层1
        keras.layers.MaxPool2D(pool_size=2,strides=2,padding="same"),
        #卷积层2
        keras.layers.Conv2D(64,kernel_size=5,strides=1,padding="same",data_format="channels_last",activation=tf.nn.relu),
        #池化层2
        keras.layers.MaxPool2D(pool_size=2,strides=2,padding="same"),
        #数据整理
        keras.layers.Flatten(),
        #1024个,全连接层
        keras.layers.Dense(1024,activation=tf.nn.relu),
        #100个,全连接层
        keras.layers.Dense(100,activation=tf.nn.softmax)
    ])

    def __init__(self):
        (self.x_train,self.y_train),(self.x_test,self.y_test) = cifar100.load_data()

        self.x_train = self.x_train/255.0
        self.x_test = self.x_test/255.0


    def compile(self):
        CNNMnist.model.compile(optimizer=keras.optimizers.Adam(),loss=keras.losses.sparse_categorical_crossentropy,metrics=["accuracy"])

    def fit(self):
        CNNMnist.model.fit(self.x_train,self.y_train,epochs=1,batch_size=32)

    def evaluate(self):
        test_loss,test_acc = CNNMnist.model.evaluate(self.x_test,self.y_test)
        print(test_loss,test_acc)

if __name__ == '__main__':
    cnn = CNNMnist()
    print(CNNMnist.model.summary())
    cnn.compile()
    cnn.fit()

  

你可能感兴趣的:(TensorFlow keras卷积神经网络 添加L2正则化)