使用Keras搭建一个CNN处理MNIST数据

该博客介绍了如何利用Keras库构建一个卷积神经网络(CNN)来处理MNIST数据集,参考了GitHub上的U-Net结构,将网络结构和训练分开,使代码更清晰。内容包括代码结构的描述以及Keras实现CNN的步骤。
摘要由CSDN通过智能技术生成

代码结构

这里主要是参考了github上面一个u-net的程序的结构。链接
在项目中,程序员将整个神经网络分成了网络结构和训练两个类,并定义了一些函数来完成类似混淆矩阵生成这样的操作。
在这里,也是模仿了他的写法,这样会显得清晰一些。

代码

这里使用Keras库,采用的是Functional API的搭建网络方式:


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 15 10:03:52 2017

a simple cnn classifier for mnist data using Functional API


@author: huijian
"""
from __future__ import print_function

import numpy as np
# set the seed for reproducibility
np.random.seed(1234)

from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt

# the libraries of keras
from keras.datasets import mnist
from keras.models import Sequential, Model
from keras.models import model_from_json
from keras.layers import Input
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils

from keras import backend as K
K.set_image_dim_ordering("tf")
"""
for a picture of a form (128,128,3) (img_row, img_col, channels)
th: (3,128,128) (channels,img_row,img_col)
tf: (128,128,3) (img_row, img_col, channels)
"""

def create_conv(img_shape, num_classes):
    """
    param:
    img_shape: a 1-D tensor, [img_row, img_col, channels]
    """
    inputs = Input(shape=(img_shape[0], img_shape[1], img_shape[2]))
    conv1 = Conv2D(filters = 30, kernel_size = [5,
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值