zoukankan      html  css  js  c++  java
  • 用Keras搭建神经网络 简单模版(二)——Classifier分类(手写数字识别)


    #
    -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) #for reproducibility再现性 from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential#按层 from keras.layers import Dense, Activation#全连接层 import matplotlib.pyplot as plt from keras.optimizers import RMSprop

    从mnist下载手写数字图片数据集,图片为28*28,将每个像素的颜色(0到255)改为(0倒1),将标签y变为10个长度,若为1,则在1处为1,剩下的都标为0。

    #dowmload the mnisst the path '~/.keras/datasets/' if it is the first time to be called
    #x shape (60000 28*28),y shape(10000,)
    (x_train,y_train),(x_test,y_test) = mnist.load_data()#0-9的图片数据集
    
    #data pre-processing
    x_train = x_train.reshape(x_train.shape[0],-1)/255 #normalize 到【0,1】
    x_test = x_test.reshape(x_test.shape[0],-1)/255
    y_train = np_utils.to_categorical(y_train, num_classes=10) #把标签变为10个长度,若为1,则在1处为1,剩下的都标为0
    y_test = np_utils.to_categorical(y_test,num_classes=10)

     

    搭建神经网络,Activation为激活函数。由于第一个Dense传出32.所以第二个的Dense默认传进32,不用特意设置。

    #Another way to build neural net
    model = Sequential([
            Dense(32,input_dim=784),#传出32
            Activation('relu'),
            Dense(10),
            Activation('softmax')
            ])
    
    #Another way to define optimizer
    rmsprop = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0)
    
    # We add metrics to get more results you want to see
    model.compile( #编译
            optimizer = rmsprop,
            loss = 'categorical_crossentropy',
            metrics=['accuracy'], #在更新时同时计算一下accuracy
            )

     

    训练和测试

    print("Training~~~~~~~~")
    #Another way to train the model
    model.fit(x_train,y_train, epochs=2, batch_size=32) #训练2大批,每批32个
    
    print("
    Testing~~~~~~~~~~")
    #Evalute the model with the  metrics we define earlier
    loss,accuracy = model.evaluate(x_test,y_test)
    
    print('test loss:',loss)
    print('test accuracy:', accuracy)

     

    全代码:

    # -*- coding: utf-8 -*-
    import numpy as np
    np.random.seed(1337) #for reproducibility再现性
    from keras.datasets import mnist
    from keras.utils import np_utils
    from keras.models import Sequential#按层
    from keras.layers import Dense, Activation#全连接层
    import matplotlib.pyplot as plt
    from keras.optimizers import RMSprop
    
    #dowmload the mnisst the path '~/.keras/datasets/' if it is the first time to be called
    #x shape (60000 28*28),y shape(10000,)
    (x_train,y_train),(x_test,y_test) = mnist.load_data()#0-9的图片数据集
    
    #data pre-processing
    x_train = x_train.reshape(x_train.shape[0],-1)/255 #normalize 到【0,1】
    x_test = x_test.reshape(x_test.shape[0],-1)/255
    y_train = np_utils.to_categorical(y_train, num_classes=10) #把标签变为10个长度,若为1,则在1处为1,剩下的都标为0
    y_test = np_utils.to_categorical(y_test,num_classes=10)
    
    #Another way to build neural net
    model = Sequential([
            Dense(32,input_dim=784),#传出32
            Activation('relu'),
            Dense(10),
            Activation('softmax')
            ])
    
    #Another way to define optimizer
    rmsprop = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0)
    
    # We add metrics to get more results you want to see
    model.compile( #编译
            optimizer = rmsprop,
            loss = 'categorical_crossentropy',
            metrics=['accuracy'], #在更新时同时计算一下accuracy
            )
    
    print("Training~~~~~~~~")
    #Another way to train the model
    model.fit(x_train,y_train, epochs=2, batch_size=32) #训练2大批,每批32个
    
    print("
    Testing~~~~~~~~~~")
    #Evalute the model with the  metrics we define earlier
    loss,accuracy = model.evaluate(x_test,y_test)
    
    print('test loss:',loss)
    print('test accuracy:', accuracy)
    View Code

    结果为:

     

  • 相关阅读:
    线程同步的三种方式(Mutex,Event,Critical Section) 沧海
    VC++多线程下内存操作的优化 沧海
    C++内存对象大会战 沧海
    技术关注:搜索引擎经验 沧海
    jira 3.13.5版 安装 配置 用户权限控制 拂晓风起
    C++ int string 转换 拂晓风起
    C++调用C链接库会出现的问题 拂晓风起
    Windows Server 2003 IIS Service Unavailable 问题解决 拂晓风起
    研究 学术 开发 的好用工具(不包括常见的) 拂晓风起
    SGMarks 问世 (Firefox扩展Gmarks的扩展版) 纯属学习 拂晓风起
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/9603014.html
Copyright © 2011-2022 走看看