import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import models
from tensorflow.keras import datasets,Sequential,layers,optimizers,metrics
from tensorflow.keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Reshape
print(tf.__version__)
#数据预处理
def proprocess(x,y):
x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32)
return x,y
#构建数据集对象,方便对数据的打乱,批处理等超操作
batch_size = 32
#load data
(x_train,y_train),(x_test,y_test) = datasets.mnist.load_data()
#构建网络中用到的权重
def Model():
model = models.Sequential()
model.add(Reshape((28,28,1),input_shape=(28,28)))
model.add(Conv2D(32,(3,3),activation='relu'))
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'))
return model
if __name__ == '__main__':
#gpu config
# physical_devices = tf.config.experimental.list_logical_devices('GPU')
# tf.config.experimental.set_memory_growth(device=physical_devices[0],enable=True)
#load data
(x_train,y_train),(x_test,y_test) = datasets.mnist.load_data()
#get CNN model
model =Model()
#show
model.summary()
#train
model.compile(optimizers.SGD(0.005),loss = 'sparse_categorical_crossentropy',metrics=['accuracy'])
model.fit(
x_train,
y_train,
batch_size=32,
epochs=30)
#test
test_loss,test_acc = model.evaluate(x_test,y_test)
print(test_acc)
RNN例程
最新推荐文章于 2024-03-19 10:30:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)