About
CNNNNNN
-- coding: utf-8 --
"""FINAL CNN.ipynb
Automatically generated by Colaboratory.
Original file is located at https://colab.research.google.com/drive/1ii3cfL7neL_rDLG_WmwPMvMRQz8sWO6q
- Loading the dataset
1.a) """
import numpy as np import matplotlib.pyplot as plt from keras.datasets import fashion_mnist from keras.utils import to_categorical
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
"""1.b)"""
train_images = train_images.astype('float32') / 255.0 test_images = test_images.astype('float32') / 255.0
Reshape images to (28, 28, 1) for compatibility with ConvNet
train_images = np.expand_dims(train_images, axis=-1) test_images = np.expand_dims(test_images, axis=-1)
"""1.c)"""
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=(6, 6)) for i in range(9): plt.subplot(3, 3, i + 1) plt.imshow(train_images[i].reshape(28, 28), cmap= 'gray') plt.axis('off') plt.show()
"""2- CNN CONSTRUCTION
2.a) """
from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
Create the model
model = Sequential()
Convolutional layers with pooling
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(128, (3, 3), activation='relu'))
Flatten the output and add fully connected layers
model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dense(128, activation='relu')) model.add(Dense(10, activation='relu'))
summary
model.summary()
"""2.b)"""
Compile the model
model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
Fit the model
history = model.fit(train_images, train_labels, epochs=10, batch_size=128, validation_split=0.1)
"""3-PERFORMANCE EVALUATION
3.a) """
Plot accuracy
plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend(['Train', 'Validation'], loc='upper left') plt.show()
Plot loss
plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend(['Train', 'Validation'], loc='upper left') plt.show()
test_lossa, test_accuracyb = model.evaluate(test_images, test_labels)
Print test set accuracy and loss for the model trained with 10 epochs and batch size 128
print("Model 1 Test Accuracy:", test_accuracyb) print("Model 1 Test Loss:", test_lossa)
"""3.b)"""
Fit the model with modified parameters
history = model.fit(train_images, train_labels, epochs=11, batch_size=256, validation_split=0.1)
Plot accuracy
plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend(['Train', 'Validation'], loc='upper left') plt.show()
Plot loss
plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend(['Train', 'Validation'], loc='upper left') plt.show()
"""3.c)"""
Evaluate the model on the test set
test_loss, test_accuracy = model.evaluate(test_images, test_labels)
Print test set accuracy and loss for the model trained with 10 epochs and batch size 128
print("Model 1 Test Accuracy:", test_accuracy) print("Model 1 Test Loss:", test_loss)
Evaluate the model on the test set for the modified model
test_loss2, test_accuracy2 = model.evaluate(test_images, test_labels)
Print test set accuracy and loss for the model trained with 15 epochs and batch size 256
print("Model 2 Test Accuracy:", test_accuracy2) print("Model 2 Test Loss:", test_loss2)
RNNNNN
-- coding: utf-8 --
"""FINAL RNN_PYTHON.ipynb
Automatically generated by Colaboratory.
Original file is located at https://colab.research.google.com/drive/1NonvGl1OeSn2NfrVaJnUKimxf2r-bGpv
IMPORTING LIB """
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)
"""LOADING DATA SET"""
(xtrain,ytrain),(xtest,ytest) = imdb.load_data(num_words=5000)
"""PREPROCESSING DATA"""
padding sequence to a fixed length
max_length = 100 xtrain = sequence.pad_sequences(xtrain,maxlen=100) xtest = sequence.pad_sequences(xtest,maxlen=100)
"""MODELL CREATION"""
creating rnn model
max_words = 5000
model = Sequential() model.add(Embedding(5000,32,input_length = 100)) model.add(LSTM(100)) model.add(Dense(1,activation = 'sigmoid')) model.summary()
"""COMPILE MODELL"""
Compile the modelmm
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Train the model
batch_size = 64 epochs = 5 history = model.fit(xtrain, ytrain, batch_size=batch_size, epochs=epochs, validation_data=(xtest, ytest))
import matplotlib.pyplot as plt
plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label = 'val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(xtest, ytest, verbose=0)
Evaluate the model
scores = model.evaluate(xtest, ytest, verbose=0) print('Test loss:', scores[0]) print('Test accuracy:', scores[1])
AUTO ENCODERS
-- coding: utf-8 --
"""FINAL Auto_encoders.ipynb
Automatically generated by Colaboratory.
Original file is located at https://colab.research.google.com/drive/1mQVPDhacmMsKD2hINHCUgf2Fkzfo8OYw """
import numpy as np from tensorflow import keras from tensorflow.keras import layers
(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()
ANB CNNN
-- coding: utf-8 --
"""anb CNN.ipynb
Automatically generated by Colaboratory.
Original file is located at https://colab.research.google.com/drive/1837Ky10s_fgt8VE245wP2XP3pBpL5Tj6 """
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
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(64, (3, 3), activation='relu'))
model.summary()
model.add(layers.Flatten()) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(10))
model.summary()
model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label = 'val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.ylim([0.5, 1]) plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(test_acc)