tensorflow+keras搭建神经网络实现cifar100的训练

27 篇文章 1 订阅
1 篇文章 0 订阅

coding=utf-8

“”"
author:lei
function:
“”"

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

class CNNCifar(object):

# 定义模型
model = keras.Sequential([
    # 卷积层1  32个 5*5*3的filter strides=1 padding=same
    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),

    # 卷积层2
    keras.layers.Conv2D(64, kernel_size=5, strides=1, padding="same", data_format="channels_last", activation=tf.nn.relu),

    keras.layers.MaxPool2D(pool_size=2, strides=2),

    # 全连接层 先扁平化
    keras.layers.Flatten(),

    # 1024个神经网络 全连接层
    keras.layers.Dense(1024, activation=tf.nn.relu),

    # 加入dropout
    keras.layers.Dropout(0.2),

    # 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
    self.x_test = self.x_test / 255

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

    return None

def fit(self):
    CNNCifar.model.fit(self.x_train, self.y_train, epochs=1, batch_size=64)

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

    print("test:", test_loss, test_acc)

if name == ‘main’:
cnn = CNNCifar()
# print(CNNCifar.model.summary())
cnn.compile()
cnn.fit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值