Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- WEEK -6
- import matplotlib.pyplot as plt
- import numpy as np
- import pandas as pd
- %matplotlib inline
- from sklearn.datasets import load_breast_cancer
- cancer=load_breast_cancer()
- cancer.keys()
- dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', ' ‘ feature_names',
- 'filename','data_module'])
- print(cancer['DESCR'])
- # ------------------------------------
- df=pd.DataFrame(cancer['data'],columns=cancer['feature_names'])
- df.head(5)
- # ------------------------------------
- from sklearn.preprocessing import
- StandardScalerscaler=StandardScaler()
- scaler.fit(df)
- StandardScaler
- StandardScaler()
- scaled_data=scaler.transform(df)
- scaled_data
- # ------------------------------------
- from sklearn.decomposition
- import PCA
- pca=PCA(n_components=2)
- pca.fit(scaled_data)
- PCA
- PCA(n_components=2)
- x_pca=pca.transform(scaled_data)
- scaled_data.shape
- (569, 30)
- x_pca.shape
- (569,2)
- scaled_data
- # ------------------------------------
- x_pca
- # ------------------------------------
- plt.figure(figsize=(8,6))
- plt.scatter(x_pca[:,0],x_pca[:,1],c=cancer['ta
- rget'])plt.xlabel('First principle component')
- plt.ylabel('Second principle component')
- Text(0, 0.5, 'Second principle component')
- week 7
- import numpyas np
- import pandas
- as pd
- from keras.models import Sequential
- from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
- from keras.datasets import mnist
- (x_train, y_train), (x_test, y_test) =mnist.load_data()
- print(x_train.shape)
- print(x_test.shape)
- # ------------------------------------
- x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
- x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
- print(x_train.shape)
- # ------------------------------------
- x_train = x_train.astype('float32')
- x_test = x_test.astype('float32')
- x_train /= 255
- x_test /= 255
- print(y_train.shape)
- print(y_train[:10])
- # -----------------------------------
- from keras.utils import np_utils
- y_train = np_utils.to_categorical(y_train, 10)
- Y_test = np_utils.to_categorical(y_test, 10)
- print(y_train.shape)
- print(y_train)
- # -----------------------------------
- model = Sequential()
- model.add(Conv2D(28, kernel_size=(3,3), activation = 'relu', input_shape = (28, 28, 1)))
- model.add(MaxPooling2D(pool_size=(2, 2)))
- model.add(Flatten())
- model.add(Dense(128, activation = 'relu'))
- model.add(Dense(10,activation = 'softmax'))
- model.compile(optimizer='adam', loss = 'mean_squared_error', metrics=['accuracy'])
- model.fit(x_train, y_train, epochs = 5)
- # -----------------------------------
- image_index = 5555
- from matplotlib import pyplot as plt
- plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
- pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
- print(pred.argmax())
- WEEK 8
- from keras.datasets import fashion_mnist
- from tensorflow.keras.models import Sequential
- from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten
- from tensorflow.keras.optimizers import Adam
- import matplotlib.pyplot as plt
- import numpy as np
- # Split the data into training and testing
- (trainX, trainy), (testX, testy) = fashion_mnist.load_data()
- # Print the dimensions of the dataset
- print('Train: X = ', trainX.shape)
- print('Test: X = ', testX.shape)
- # -----------------------------------
- for i in range(1, 10):
- # Create a 3x3 grid and
- place the# image in ith
- position of grid
- plt.subplot(3, 3, i)
- # Insert ith image with the color map 'grap'
- plt.imshow(trainX[i],
- cmap=plt.get_cmap('gray'))
- # Display the
- entire plot
- plt.show()
- # -----------------------------------
- trainX = np.expand_dims(trainX, -1)
- testX = np.expand_dims(testX, -1)
- print(trainX.shape)
- # -----------------------------------
- def model_arch():
- models = Sequential()
- # We are learning 64
- # filters with a kernel size of 5x5
- models.add(Conv2D(64, (5, 5),
- padding="same",
- activation="relu",
- input_shape=(28, 28, 1)))
- # Max pooling will reduce the
- # size with a kernel size of 2x2
- models.add(MaxPooling2D(pool_size=(2, 2)))
- models.add(Conv2D(128, (5, 5), padding="same",activation="relu"))
- models.add(MaxPooling2D(pool_size=(2, 2)))
- models.add(Conv2D(256, (5, 5),
- padding="same",
- activation="relu"))
- models.add(MaxPooling2D(pool_size=(2, 2)))
- # Once the convolutional and pooling
- # operations are done the layer
- # is flattened and fully connected
- layers
- # are added
- models.add(Flatten())
- models.add(Dense(256, activation="relu"))
- # Finally as there are total 10
- # classes to be added a FCC layer of
- # 10 is created with a softmax
- activation# function
- models.add(Dense(10, activation="softmax"))
- return models
- model = model_arch()
- model.compile(optimizer=Adam(learning_rate=1e-3),
- loss='sparse_categorical_crossentropy',
- metrics=['sparse_categorical_accuracy'])
- model.summary()
- # -----------------------------------
- history = model.fit(
- trainX.astype(np.float32), trainy.astype(np.float32),
- epochs=10,
- steps_per_epoch=100,
- validation_split=0.33
- )
- # -----------------------------------
- # Accuracy vs Epoch plot
- plt.plot(history.history['sparse_categorical_accuracy'])
- plt.plot(history.history['val_sparse_categorical_accuracy'])
- plt.title('Model Accuracy')
- plt.ylabel('Accuracy')
- plt.xlabel('epoch')
- plt.legend(['train', 'val'], loc='upper left')
- plt.show()
- # -----------------------------------
- # Loss vs Epoch plot
- plt.plot(history.history['loss'])
- plt.plot(history.history['val_loss'])
- plt.title('Model Accuracy')
- plt.ylabel('loss')
- plt.xlabel('epoch')
- plt.legend(['train', 'val'], loc='upper left')
- plt.show()
- # -----------------------------------
- # There are 10 output labels for the Fashion MNIST dataset
- labels = ['t_shirt', 'trouser', 'pullover', 'dress', 'coat',
- 'sandal', 'shirt', 'sneaker', 'bag', 'ankle_boots']
- # Make a prediction
- predictions = model.predict(testX[:1])
- label = labels[np.argmax(predictions)]
- print(label)
- plt.imshow(testX[:1][0])
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement