初学者的 TensorFlow 2.0 教程

1. 加载一个预构建的数据集。
2. 构建对图像进行分类的神经网络机器学习模型。
3. 训练此神经网络。
4. 评估模型的准确率。

1. 在 Colab中, 连接到Python运行环境： 在菜单条的右上方, 选择 CONNECT
2. 运行所有的代码块: 选择 Runtime > Run all

设置 TensorFlow

``````import tensorflow as tf
``````

加载数据集

``````mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
``````

构建机器学习模型

``````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)
])
``````

``````predictions = model(x_train[:1]).numpy()
predictions
``````

`tf.nn.softmax` 函数将这些 logits 转换为每个类的概率

``````tf.nn.softmax(predictions).numpy()
``````

``````loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
``````

``````loss_fn(y_train[:1], predictions).numpy()
``````

``````model.compile(optimizer='adam',
loss=loss_fn,
metrics=['accuracy'])
``````

训练并评估模型

``````model.fit(x_train, y_train, epochs=5)
``````

`Model.evaluate` 方法通常在 "Validation-set" 或 "Test-set" 上检查模型性能。

``````model.evaluate(x_test,  y_test, verbose=2)
``````

``````probability_model = tf.keras.Sequential([
model,
tf.keras.layers.Softmax()
])
``````
``````probability_model(x_test[:5])
``````

[]
[]