About
1a
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np import matplotlib.pyplot as plt (x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data()
1b
x_train = x_train / 255.0 x_test = x_test / 255.0
1c
print("x_train shape:", x_train.shape) print("y_train shape:", y_train.shape) print("x_test shape:", x_test.shape) print("y_test shape:", y_test.shape) plt.figure(figsize=(10, 4)) for i in range(10): plt.subplot(2, 5, i+1) plt.imshow(x_train[i]) plt.title(f"Label: {y_train[i]}") plt.tight_layout() plt.show()
2a
model = keras.Sequential([ layers.Conv2D(64, (3, 3), activation='relu', input_shape=(32, 32, 3)), layers.MaxPooling2D((2, 2)), layers.Conv2D(128, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Flatten(), layers.Dense(256, activation='relu'), layers.Dense(100) ])
2b
model.compile(optimizer='adagrad', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) history = model.fit(x_train, y_train, epochs=12, batch_size=128, validation_split=0.2)
3a
plt.plot(history.history['accuracy'], label='training accuracy') plt.plot(history.history['val_accuracy'], label='validation accuracy') plt.title('Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() plt.plot(history.history['loss'], label='training loss') plt.plot(history.history['val_loss'], label='validation loss') plt.title('Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show()
test_loss_2, test_acc_2 = model.evaluate(x_test, y_test, verbose=2)
import numpy as np from tensorflow.keras.datasets import imdb from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense from tensorflow.keras.preprocessing import sequence
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) = imdb.load_data(num_words=max_words)
Pad sequences to a fixed length
max_length = 100 x_train = sequence.pad_sequences(x_train, maxlen=max_length) x_test = sequence.pad_sequences(x_test, maxlen=max_length)
Create the RNN model
model = Sequential() model.add(Embedding(max_words, 32, input_length=max_length)) model.add(LSTM(100)) model.add(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 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])
import numpy as np from tensorflow import keras from tensorflow.keras import layers
Load the MNIST dataset
(x_train, _), (x_test, _) = keras.datasets.mnist.load_data()
Normalize and reshape the input data
x_train = x_train.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 x_train = np.reshape(x_train, (len(x_train), 28, 28, 1)) x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
Define the autoencoder model
input_img = keras.Input(shape=(28, 28, 1)) encoded = layers.Flatten()(input_img) 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=10, batch_size=128, shuffle=True, validation_data=(x_test, x_test))
Test the autoencoder
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)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)
Decoded images
ax = plt.subplot(2, n, i + 1 + n) plt.imshow(decoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()