神经网络中基于Keras实现包含全局池化的卷积神经网络

利用Keras组件,完成CNN模型的快速搭建,并完成图像分类任务。

代码:

#导入所需库
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
from keras.callbacks import EarlyStopping
from keras.datasets import mnist
from keras.utils import to_categorical
import matplotlib.pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

#导入数据
help(mnist)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
assert x_train.shape == (60000, 28, 28)
assert x_test.shape == (10000, 28, 28)
assert y_train.shape == (60000,)
assert y_test.shape == (10000,)
import numpy as np
index=np.random.randint(0,x_train.shape[0])
digit=x_train[index]
plt.imshow(digit)
print(y_train[index])

#数据预处理
x_train=x_train.reshape((60000,28,28,1))
x_train=x_train.astype('float32')/255
x_test=x_test.reshape((10000,28,28,1))
x_test=x_test.astype('float32')/255
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)


#搭建网络
help(Conv2D)
inputs=Input(shape=(28,28,1))

from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense

# 定义模型结构
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax'))

# 查看模型结构
model.summary()

#编译
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

#训练
history=model.fit(x_train, y_train, epochs=5, batch_size=64,validation_split=0.02)
print(history)

#测试
test_loss, test_acc = model.evaluate(x_test, y_test)
test_acc 

loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training&Validation loss')
plt.legend()
plt.show()


acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
epochs = range(1, len(loss) + 1)
plt.figure()
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training&Validation acc')
plt.legend()
plt.show()






截图

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张謹礧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值