About
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()
train_images, test_images = train_images / 255.0 , test_images /255.0
print("Train images shape:", train_images.shape) print("Train labels shape:", train_labels.shape) print("Test images shape:", test_images.shape) print("Test labels shape:", test_labels.shape)
plt.figure(figsize=(4,4)) for i in range (16): plt.subplot(4,4,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i], cmap=plt.cm.binary) plt.xlabel(train_labels[i][0]) plt.show()
from tensorflow.keras import layers, models 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.add(layers.MaxPooling2D(2,2)) 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()
import tensorflow as tf model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10, batch_size=64, validation_split=0.1)
plt.plot(history.history['accuracy'], label='Training accuracy') plt.plot(history.history['val_accuracy'], label='Validation accuracy') plt.plot(history.history['loss'], label='Training loss') plt.plot(history.history['val_loss'], label='Validation loss') plt.xlabel('Epoch') plt.ylabel('Accuracy/Loss') plt.legend() plt.show()
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print("Model 1 - Test accuracy:", test_acc) print("Model 1 - Test loss:", test_loss)
RNN
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
np.random.seed(42) max_words = 5000
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_words)
max_length = 100 x_train = sequence.pad_sequences(x_train, maxlen=max_length) x_test = sequence.pad_sequences(x_test, maxlen=max_length)
model = Sequential() model.add(Embedding(max_words, 32, input_length=max_length)) model.add(LSTM(100)) model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary()) batch_size = 64 epochs = 5 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test))
scores = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', scores[0]) print('Test accuracy:', scores[1])
AE
from keras.layers import Dense,Conv2D,MaxPooling2D,UpSampling2D from keras import Input, Model from keras.datasets import mnist import numpy as np import matplotlib.pyplot as plt
encoding_dim = 15 input_img = Input(shape=(784,)) encoded = Dense(encoding_dim, activation='relu')(input_img) decoded = Dense(784, activation='sigmoid')(encoded) autoencoder = Model(input_img, decoded)
encoder = Model(input_img, encoded) encoded_input = Input(shape=(encoding_dim,)) decoder_layer = autoencoder.layers[-1] decoder = Model(encoded_input, decoder_layer(encoded_input))
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
(x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:]))) x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:]))) print(x_train.shape) print(x_test.shape)
plt.imshow(x_train[0].reshape(28,28))
autoencoder.fit(x_train, x_train,epochs=2,batch_size=256,validation_data=(x_test, x_test))
encoded_img = encoder.predict(x_test) decoded_img = decoder.predict(encoded_img) plt.figure(figsize=(20, 4)) for i in range(5): ax = plt.subplot(2, 5, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)
Display reconstruction
ax = plt.subplot(2, 5, i + 1 + 5) plt.imshow(decoded_img[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()
encoded_img = encoder.predict(x_test) decoded_img = decoder.predict(encoded_img) plt.figure(figsize=(20, 4)) for i in range(5):
Display original
ax = plt.subplot(2, 5, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)
Display reconstruction
ax = plt.subplot(2, 5, i + 1 + 5) plt.imshow(decoded_img[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()
plt.figure(figsize=(20, 2)) for i in range(1, 5 + 1): ax = plt.subplot(1, 5, i) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()
noise_factor = 0.7 x_train_noisy = x_train + noise_factor np.random.normal(loc=0.0, scale=1.0, size=x_train x_test_noisy = x_test + noise_factor np.random.normal(loc=0.0, scale=1.0, size=x_test.sh x_train_noisy = np.clip(x_train_noisy, 0., 1.) x_test_noisy = np.clip(x_test_noisy, 0., 1.)