About
Cifar10
import tensorflow as tf
from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
train_images[1].shape
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(10,10))
for i in range(25): plt.subplot(5,5,i+1)
# plt.xticks([])
# plt.yticks([])
# plt.grid(False)
plt.imshow(train_images[i])
# The CIFAR labels happen to be arrays,
# which is why you need the extra index
# plt.xlabel(class_names[train_labels[i][0]])
plt.show()
model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.summary()
model.add(layers.Flatten()) model.add(layers.Dense(256, activation='relu')) model.add(layers.Dense(128, activation='relu')) model.add(layers.Dense(10))
model.summary()
model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=2, validation_data=(test_images, test_labels),batch_size=64)
plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label = 'val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy')
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(test_acc)
RNN
import numpy as np import numpy as np import tensorflow as tf from tensorflow.keras import layers,datasets,models,preprocessing import matplotlib.pyplot as plt
Set random seed for reproducibility
np.random.seed(42)
Set the maximum number of words to be used (vocabulary size)
max_words = 5000
Load the IMDB dataset
(x_train, y_train), (x_test, y_test) = datasets.imdb.load_data(num_words=max_words)
len(x_train[1])
Pad sequences to a fixed length
max_length = 100 x_train = preprocessing.sequence.pad_sequences(x_train, maxlen=max_length) x_test = preprocessing.sequence.pad_sequences(x_test, maxlen=max_length)
x_train[1]
Create the RNN model
model = models.Sequential() model.add(layers.Embedding(max_words, 32, input_length=max_length)) model.add(layers.LSTM(100)) model.add(layers.Dense(1, activation='sigmoid'))
Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Print the model summary
print(model.summary())
Train the model
batch_size = 64 epochs = 5 history=model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test))
Evaluate the model
scores = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', scores[0]) print('Test accuracy:', scores[1])
plt.plot(history.history['accuracy'],label='accuracy') plt.plot(history.history['val_accuracy'],label='val_accuracy') plt.legend()
Auto
import numpy as np from tensorflow import keras from tensorflow.keras import layers,datasets,models
Load the MNIST dataset
(x_train, _), (x_test, _) = datasets.mnist.load_data()
Normalize and reshape the input data
x_train = x_train/ 255.0 x_test = x_test/ 255.0
x_train.shape
Define the autoencoder model
input_img = keras.Input(shape=(28, 28, 1)) encoded = layers.Flatten()(input_img) encoded = layers.Dense(784, activation='sigmoid')(encoded) encoded = layers.Dense(64, activation='relu')(encoded) decoded = layers.Dense(784, activation='sigmoid')(encoded) decoded = layers.Reshape((28, 28, 1))(decoded)
autoencoder = keras.Model(input_img, decoded) autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
autoencoder.summary()
from tensorflow.keras.utils import plot_model plot_model(autoencoder, to_file='model_visualization.png', show_shapes=True)
Train the autoencoder
autoencoder.fit(x_train, x_train, epochs=1, batch_size=128, shuffle=True, validation_data=(x_test, x_test))
decoded_imgs = autoencoder.predict(x_test)
Display some results
import matplotlib.pyplot as plt n = 10 # Number of digits to display plt.figure(figsize=(20, 4)) for i in range(n):
Original images
ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i].reshape(28, 28))
Decoded images
ax = plt.subplot(2, n, i + 1 + n) plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.show()