# author: Roy.G
# author: Roy.G
from keras.datasets import mnist
import matplotlib.pyplot as plt
from keras.utils.np_utils import to_categorical #import to_categorical
import numpy as np
from keras.models import Sequential as sq
from keras.layers import Dense as dn
from keras.layers import Conv2D as cd
from keras.layers import AveragePooling2D as ap
from keras.layers import Flatten as fl
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" #设置不用gpu进行训练,因为gpu不知道为啥会出错
import tensorflow as tf
# config = tf.ConfigProto()
config =tf.compat.v1.ConfigProto()
# 使用CUDA10.1加上Tensorflow2.0会出现AttributeError: module'tensorflow'has no attribute'ConfigProto'
# 这个问题,这个是由于现在新版本中一些1.0版本的函数被和2.0版本函数区分开的缘故所以,需要将tf.ConfigProto修改为tf.compat.v1.ConfigProto
config.gpu_options.per_process_gpu_memory_fraction = 0.4 #占用40%显存
session = tf.compat.v1.Session(config=config)
(x_train,y_train),(xt,yt)=mnist.load_data()
x_train=x_train.reshape(60000,28,28,1)/255
xt=xt.reshape(10000,28,28,1)/255
y_train=to_categorical(y_train,10) # 将输入转换为one hot 格式的数据
yt=to_categorical(yt,10)
# 1. 建立模型
model = sq() #实体化全连接模型
# 2.建立神经元
# dense = dn(units=2,activation='sigmoid',input_dim=1)# 可以直接用下面的参数写入
# 3.将神经元加入模型
model.add(cd(filters=6,kernel_size=(5,5),strides=(1,1),input_shape=(28,28,1),padding='valid',activation='relu'))
# fiters=6,卷积核,kernal_size=(5,5)卷积核面积,strides=(1,1),步长,input_shape=(28,28,1),数据的形状和数据的维度(图片的颜色维度?)
# ,padding='valid',填充方式,same为同样大小,valid为逐渐变小,activation='relu',神经网络的激活函数)
model.add(ap(pool_size=(2,2)))
#池化层大小
model.add(cd(filters=16,kernel_size=(5,5),strides=(1,1),padding='valid',activation='relu'))
#input 没必要了
model.add(ap(pool_size=(2,2)))
model.add(fl())
#添加平铺层
model.add(dn(units=120,activation='relu'))
model.add(dn(units=84,activation='relu'))
#添加神经网络
model.add(dn(units=10,activation='softmax'))
#添加输出层
model.compile(loss='categorical_crossentropy',optimizer=tf.keras.optimizers.SGD(0.05),metrics=['accuracy'])
# loss=代价函数,sgd=随机梯度下降算法,metrics=['accuracy],categorical_crossentropy'=交叉商函数
model.fit(x_train,y_train,epochs=5000,batch_size=2048) #batch_size=每次训练所使用的样本数量
loss,accuracy=model.evaluate(xt,yt)
#5. 验证模型、
pres=model.predict(x_train)
# 6.训练模型
mg=model.get_weights()
print(mg)
print('envaluate',loss,accuracy)