大佬教程收集整理的这篇文章主要介绍了TensorFlow 2 quickstart for experts,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Import TensorFlow into your program:
import tensorflow as tffrom tensorflow.keras.layers import Dense, Flatten, Conv2Dfrom tensorflow.keras import Model
Load and prepare the MNIST dataset.
@H_441_1@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# Add a chAnnels dimensionx_Train = x_Train[..., tf.newaxis].astype("float32")x_test = x_test[..., tf.newaxis].astype("float32")
Use tf.data to batch and shuffle the dataset:
Train_ds = tf.data.Dataset.from_tensor_slices( (x_Train, y_Train)).shuffle(10000).batch(32)test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
Build the tf.keras model using the Keras model subclassing API:
class Mymodel(Model): def __init__(self): super(Mymodel, self).__init__() self.conv1 = Conv2D(32, 3, activation='relu') self.flatten = Flatten() self.d1 = Dense(128, activation='relu') self.d2 = Dense(10) def call(self, X): x = self.conv1(X) x = self.flatten(X) x = self.d1(X) return self.d2(X)# Create an instance of the model@H_441_1@model = Mymodel()
Choose an optimizer and loss function for Training:
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=TruE)optimizer = tf.keras.optimizers.Adam()
SELEct metrics to measure the loss and the accuracy of the model. @R_944_8270@ metrics accumulate the values over epochs and then print the overall result.
Train_loss = tf.keras.metrics.Mean(name='Train_loss')Train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='Train_accuracy')test_loss = tf.keras.metrics.Mean(name='test_loss')test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
Use tf.GradientTape to Train the model:
@tf.functiondef Train_step(images, labels): with tf.GradientTape() as tape: # Training=True is only needed if there are layers with different # behavior during Training versus inference (e.g. Dropout). preDictions = model(images, Training=TruE) loss = loss_object(labels, preDictions) gradients = tape.gradient(loss, model.Trainable_variables) optimizer.apply_gradients(zip(gradients, model.Trainable_variables)) Train_loss(loss) Train_accuracy(labels, preDictions)
Test the model:
@tf.functiondef test_step(images, labels): # Training=false is only needed if there are layers with different # behavior during Training versus inference (e.g. Dropout). preDictions = model(images, Training=falsE) t_loss = loss_object(labels, preDictions) test_loss(t_loss) test_accuracy(labels, preDictions)
EPOCHS = 5for epoch in range(EPOCHS): # Reset the metrics at the start of the next epoch Train_loss.reset_states() Train_accuracy.reset_states() test_loss.reset_states() test_accuracy.reset_states() for images, labels in Train_ds: Train_step(images, labels) for test_images, test_labels in test_ds: test_step(test_images, test_labels) print( f'Epoch {epoch + 1}, ' f'Loss: {Train_loss.result()}, ' f'Accuracy: {Train_accuracy.result() * 100}, ' f'Test Loss: {test_loss.result()}, ' f'Test Accuracy: {test_accuracy.result() * 100}' )
The image classifier is now Trained to ~98% accuracy on this dataset
代码链接: https://codechina.csdn.net/csdn_codechina/enterprise_technology/-/blob/master/CV_Classification/TensorFlow%202%20quickstart%20for%20experts.ipynb
以上是大佬教程为你收集整理的TensorFlow 2 quickstart for experts全部内容,希望文章能够帮你解决TensorFlow 2 quickstart for experts所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。