基于KERAS的多分类全连接神经网络-代码练习
需要有一定的python,神经网络基础
代码
去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片
.
// An highlighted block
#基于tensorflow去搭建神经网络框架
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential, Model
from keras.layers.core import Dense,Activation, Dropout
from keras.utils import np_utils
import matplotlib.pyplot as plt
import matplotlib.image as processimage
#Load mnist RAW datasets 拉取原始数据
(X_train, Y_train),(X_test,Y_test) = mnist.load_data()
print (X_train.shape,Y_train.shape)
print (X_test.shape, Y_test.shape)
#prepare 准备数据
#reshape
X_train = X_train.reshape(60000,784)
X_test = X_test.reshape(10000,784)
#set type into float32 设置成浮点型
X_train = X_train.astype('float32') #astype set as type into
X_test = X_test.astype('float32')
#归一化
X_train = X_train / 255
X_test /= 255
#class vectors [0,0,0,0,0,0,0,0,0,0,1,0]
Y_test = np_utils.to_categorical(Y_test,nb_class) #label
Y_train = np_utils.to_categorical(Y_train,nb_class)
#设置网络结构
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=784))
model.add(Dropout(0.2))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
# 编译 Compile
model.compile(
loss = 'categorical_crossentropy',
optimizer = 'rmsprop', #adam,SGD
metrics = ['accuracy']
)
# 启动网络训练 Fire
#prepare basic setups
batch_size = 1024 #批次
nb_class = 10
nb_epochs = 4
Training = model.fit(X_train, Y_train,
epochs=nb_epochs, batch_size = batch_size,
validation_data = (X_test,Y_test))