Skip to content

Instantly share code, notes, and snippets.

def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label
train_dataset = beans_train.map(scale).cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
eval_dataset = beans_test.map(scale).batch(BATCH_SIZE)
#Make CNN using the distributed learning algorithm
with strategy.scope():
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(16, 3, activation='relu', input_shape=(500, 500, 3)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(64, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
# Define the checkpoint directory to store the checkpoints
checkpoint_dir = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")
# Function for decaying the learning rate.
def decay(epoch):
if epoch < 3:
return 1e-3
elif epoch >= 3 and epoch < 7:
#Initializing the distributed learning algorithm
strategy = tf.distribute.MirroredStrategy()
#Defining some necessary hyperparamters
num_train_examples = info.splits['train'].num_examples
num_test_examples = info.splits['test'].num_examples
BUFFER_SIZE = 10000
BATCH_SIZE_PER_REPLICA = 32
# Import TensorFlow and TensorFlow Datasets
import tensorflow_datasets as tfds
import tensorflow as tf
#Download the dataset and divide it into train and test
datasets, info = tfds.load('beans', with_info=True, as_supervised=True)
beans_train, beans_test = datasets['train'], datasets['test']
import time
start = time.time()
model.fit(train_dataset, epochs=7, callbacks=callbacks)
end = time.time()
print("Time elapsed: {}".format(end-start))
import tensorflow as tf
# Declaring constants
x = tf.constants(4)
y = tf.constants(7)
# Performing operations
z = x + y
# Printing the result
with tf.Session() as sess:
print(sess.run(z))
import tensorflow as tf
# Declaring constants
x = tf.constants(4)
y = tf.constants(7)
# Performing operations
z = x + y
# Printing the result
print(z)
import tensorflow as tf
# Creating tensorflow constants
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[1, 2], [3, 4]])
# Summing the two tensors
c = a + b
# Printing the results
print(c)
# Converting tensor to numpy
import tensorflow as tf
# Adding the decorator
@tf.function
def matprod(x, y):
return tf.matmul(x, y)