来源:https://tensorflow.google.cn/tutorials/quickstart/beginner?hl=zh_cn
代码
import tensorflow as tf #数据导入和归一化 path=r"C:\Users\86189\Desktop\tf学习\mnist\mnist.npz" #\u代表unicode,所以要用加r mnist = tf.keras.datasets.mnist (x_train,y_train),(x_test,y_test) = mnist.load_data(path) x_train,x_test = x_train/225.0,x_test/225.0 #构建神经网络 model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28,28)), #flatten成一维 tf.keras.layers.Dense(128,activation='relu'), #全连接层,有 tf.keras.layers.Dropout(0.2), #使隐藏层的神经元以20%的概率失效 tf.keras.layers.Dense(10,activation='softmax') ]) #配置训练过程 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']) #训练并验证模型 model.fit(x_train,y_train,epochs=5) #epochs:训练过程中,训练数据被迭代的次数 model.evaluate(x_test,y_test,verbose=2) """ verbose:日志显示 verbose = 0 为不在标准输出流输出日志信息 verbose = 1 为输出进度条记录 verbose = 2 为每个epoch输出一行记录 """结果