def load_mnist(): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train = x_train.astype(float) / 255. x_test = x_test.astype(float) / 255. fields = x_train, np.squeeze(y_train) fields_test = x_test, np.squeeze(y_test) return fields, fields_test
def get_mnist(): """Returns the train and test splits of the MNIST digits dataset. x_train and x_test are shaped into the tensorflow image data shape and normalized to fit in the range [0, 1] """ (x_train, y_train), (x_test, y_test) = mnist.load_data() # reshape and standardize x arrays x_train = np.expand_dims(x_train, -1) / 255. x_test = np.expand_dims(x_test, -1) / 255. return x_train, x_test, y_train, y_test
import tensorflow as tf from tensorflow.compat.v1.keras.datasets.mnist import load_data import numpy as np # 导入MNIST数据集 # mnist = tf.keras.datasets.mnist # (x_train, y_train), (x_test, y_test) = mnist.load_data() (x_train, y_train), (x_test, y_test) = load_data(r'D:\PythonWorkspace\TFTryout\mnist.npz') # 转换为小数 # x_train, x_test = x_train / 255.0, x_test / 255.0 x_train = x_train / 255.0 x_test = x_test / 255.0 x_train_pro = np.reshape(x_train, (x_train.shape[0], -1)) x_test_pro = np.reshape(x_test, (x_test.shape[0], -1)) # 使用keras Sequential模型 model = tf.keras.models.Sequential([ # tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), # tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) sgd = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.0, nesterov=False) model.compile(optimizer=sgd, loss='sparse_categorical_crossentropy', metrics=['accuracy'])