zoukankan      html  css  js  c++  java
  • 神经网络——项目二CNN手写数字识别

     1  2 import numpy as np
     3 from keras.models import Sequential
     4 from keras.layers.core import Dense, Dropout, Activation
     5 from keras.layers import Convolution2D, MaxPooling2D, Flatten
     6 from keras.optimizers import SGD, Adam
     7 from keras.utils import np_utils
     8 from keras.datasets import mnist
     9 #categrorical_crossentropy
    10 
    11 def load_data():
    12     (x_train, y_train), (x_test, y_test) = mnist.load_data()
    13     
    14     #x_train = x_train[0:number]
    15     #y_train = y_train[0:number]
    16     x_train = x_train.reshape(x_train.shape[0], 1, 28, 28)
    17     x_test = x_test.reshape(x_test.shape[0], 1, 28, 28)
    18     x_train = x_train.astype('float32')
    19     x_test = x_test.astype('float32')
    20     # convert class vector to binary class matrices
    21     y_train = np_utils.to_categorical(y_train, 10)
    22     y_test = np_utils.to_categorical(y_test, 10)
    23     x_train = x_train
    24     x_test = x_test
    25     #x_test = np.random.normal(x_test)
    26     x_train = x_train / 255
    27     x_test = x_test / 255
    28     return (x_train, y_train), (x_test,y_test)
    29 
    30 (x_train, y_train), (x_test,y_test) = load_data()
    31 
    32 
    33 model2 = Sequential()
    34 model2.add(Convolution2D(25, 3, strides=3, input_shape=(1, 28, 28), data_format='channels_first', padding='same'))  
    35 model2.add(MaxPooling2D((2, 2))) 
    36 
    37 
    38 
    39 
    40 
    41 model2.add(Convolution2D(50, 3, strides=3, padding='same')) 
    42 model2.add(MaxPooling2D(2, 2))   
    43 
    44 
    45 model2.add(Flatten())
    46 
    47 model2.add(Dense(128, activation='relu'))
    48 model2.add(Dense(10, activation='softmax'))
    49 
    50 model2.compile(loss='mse', optimizer=SGD(lr=0.1), metrics=['accuracy'])
    51 model2.fit(x_train, y_train, batch_size=200, epochs=10, verbose=1)
    52 
    53 result = model2.evaluate(x_test, y_test, verbose=0)
    54 
    55 print('
    Test Acc:', result)

    以上demo是可以运行,但需修改parameters 

    过程所遇到的Error总结:

    1.Negative dimension size caused by subtracting 3 from 1 for 'conv2d_1/convolution' (op: 'Conv2D') .....

    2.ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_2/MaxPool' (op: 'MaxPool') with input shapes: [?,4,1,50].

    解决方案如下:

     

     

  • 相关阅读:
    Geoserver通过ajax跨域访问服务数据的方法(含用户名密码认证的配置方式)
    123
    递归____蛮好的例子 蓝桥
    博弈_____威佐夫博奕
    123123
    sort
    int ,long , long long类型的范围
    数学推导_循环小数转分数
    下一步:结构体 背包 库函数
    回溯____蓝桥 棋盘
  • 原文地址:https://www.cnblogs.com/cfancy/p/12331853.html
Copyright © 2011-2022 走看看