Advertisement
varun1729

Untitled

May 2nd, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.76 KB | None | 0 0
  1. WEEK -6
  2.  
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. import pandas as pd
  6. %matplotlib inline
  7. from sklearn.datasets import load_breast_cancer
  8. cancer=load_breast_cancer()
  9. cancer.keys()
  10. dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', ' ‘ feature_names',
  11. 'filename','data_module'])
  12. print(cancer['DESCR'])
  13. # ------------------------------------
  14. df=pd.DataFrame(cancer['data'],columns=cancer['feature_names'])
  15. df.head(5)
  16. # ------------------------------------
  17. from sklearn.preprocessing import
  18. StandardScalerscaler=StandardScaler()
  19. scaler.fit(df)
  20. StandardScaler
  21. StandardScaler()
  22. scaled_data=scaler.transform(df)
  23. scaled_data
  24. # ------------------------------------
  25. from sklearn.decomposition
  26. import PCA
  27. pca=PCA(n_components=2)
  28. pca.fit(scaled_data)
  29. PCA
  30. PCA(n_components=2)
  31. x_pca=pca.transform(scaled_data)
  32. scaled_data.shape
  33. (569, 30)
  34. x_pca.shape
  35. (569,2)
  36. scaled_data
  37. # ------------------------------------
  38. x_pca
  39. # ------------------------------------
  40. plt.figure(figsize=(8,6))
  41. plt.scatter(x_pca[:,0],x_pca[:,1],c=cancer['ta
  42. rget'])plt.xlabel('First principle component')
  43. plt.ylabel('Second principle component')
  44. Text(0, 0.5, 'Second principle component')
  45.  
  46.  
  47. week 7
  48.  
  49. import numpyas np
  50. import pandas
  51. as pd
  52. from keras.models import Sequential
  53. from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
  54. from keras.datasets import mnist
  55. (x_train, y_train), (x_test, y_test) =mnist.load_data()
  56. print(x_train.shape)
  57. print(x_test.shape)
  58. # ------------------------------------
  59. x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
  60. x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
  61. print(x_train.shape)
  62. # ------------------------------------
  63. x_train = x_train.astype('float32')
  64. x_test = x_test.astype('float32')
  65. x_train /= 255
  66. x_test /= 255
  67. print(y_train.shape)
  68. print(y_train[:10])
  69. # -----------------------------------
  70. from keras.utils import np_utils
  71. y_train = np_utils.to_categorical(y_train, 10)
  72. Y_test = np_utils.to_categorical(y_test, 10)
  73. print(y_train.shape)
  74. print(y_train)
  75. # -----------------------------------
  76. model = Sequential()
  77. model.add(Conv2D(28, kernel_size=(3,3), activation = 'relu', input_shape = (28, 28, 1)))
  78. model.add(MaxPooling2D(pool_size=(2, 2)))
  79. model.add(Flatten())
  80. model.add(Dense(128, activation = 'relu'))
  81. model.add(Dense(10,activation = 'softmax'))
  82. model.compile(optimizer='adam', loss = 'mean_squared_error', metrics=['accuracy'])
  83. model.fit(x_train, y_train, epochs = 5)
  84. # -----------------------------------
  85. image_index = 5555
  86. from matplotlib import pyplot as plt
  87. plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
  88. pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
  89. print(pred.argmax())
  90.  
  91.  
  92.  
  93. WEEK 8
  94.  
  95. from keras.datasets import fashion_mnist
  96. from tensorflow.keras.models import Sequential
  97. from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten
  98. from tensorflow.keras.optimizers import Adam
  99. import matplotlib.pyplot as plt
  100. import numpy as np
  101. # Split the data into training and testing
  102. (trainX, trainy), (testX, testy) = fashion_mnist.load_data()
  103. # Print the dimensions of the dataset
  104. print('Train: X = ', trainX.shape)
  105. print('Test: X = ', testX.shape)
  106. # -----------------------------------
  107. for i in range(1, 10):
  108. # Create a 3x3 grid and
  109. place the# image in ith
  110. position of grid
  111. plt.subplot(3, 3, i)
  112. # Insert ith image with the color map 'grap'
  113. plt.imshow(trainX[i],
  114. cmap=plt.get_cmap('gray'))
  115. # Display the
  116. entire plot
  117. plt.show()
  118. # -----------------------------------
  119. trainX = np.expand_dims(trainX, -1)
  120. testX = np.expand_dims(testX, -1)
  121. print(trainX.shape)
  122. # -----------------------------------
  123. def model_arch():
  124. models = Sequential()
  125. # We are learning 64
  126. # filters with a kernel size of 5x5
  127. models.add(Conv2D(64, (5, 5),
  128. padding="same",
  129. activation="relu",
  130. input_shape=(28, 28, 1)))
  131. # Max pooling will reduce the
  132. # size with a kernel size of 2x2
  133. models.add(MaxPooling2D(pool_size=(2, 2)))
  134. models.add(Conv2D(128, (5, 5), padding="same",activation="relu"))
  135. models.add(MaxPooling2D(pool_size=(2, 2)))
  136. models.add(Conv2D(256, (5, 5),
  137. padding="same",
  138. activation="relu"))
  139. models.add(MaxPooling2D(pool_size=(2, 2)))
  140. # Once the convolutional and pooling
  141. # operations are done the layer
  142. # is flattened and fully connected
  143. layers
  144. # are added
  145. models.add(Flatten())
  146. models.add(Dense(256, activation="relu"))
  147. # Finally as there are total 10
  148. # classes to be added a FCC layer of
  149. # 10 is created with a softmax
  150. activation# function
  151. models.add(Dense(10, activation="softmax"))
  152. return models
  153. model = model_arch()
  154. model.compile(optimizer=Adam(learning_rate=1e-3),
  155. loss='sparse_categorical_crossentropy',
  156. metrics=['sparse_categorical_accuracy'])
  157. model.summary()
  158. # -----------------------------------
  159. history = model.fit(
  160. trainX.astype(np.float32), trainy.astype(np.float32),
  161. epochs=10,
  162. steps_per_epoch=100,
  163. validation_split=0.33
  164. )
  165. # -----------------------------------
  166. # Accuracy vs Epoch plot
  167. plt.plot(history.history['sparse_categorical_accuracy'])
  168. plt.plot(history.history['val_sparse_categorical_accuracy'])
  169. plt.title('Model Accuracy')
  170. plt.ylabel('Accuracy')
  171. plt.xlabel('epoch')
  172. plt.legend(['train', 'val'], loc='upper left')
  173. plt.show()
  174. # -----------------------------------
  175. # Loss vs Epoch plot
  176. plt.plot(history.history['loss'])
  177. plt.plot(history.history['val_loss'])
  178. plt.title('Model Accuracy')
  179. plt.ylabel('loss')
  180. plt.xlabel('epoch')
  181. plt.legend(['train', 'val'], loc='upper left')
  182. plt.show()
  183. # -----------------------------------
  184. # There are 10 output labels for the Fashion MNIST dataset
  185. labels = ['t_shirt', 'trouser', 'pullover', 'dress', 'coat',
  186. 'sandal', 'shirt', 'sneaker', 'bag', 'ankle_boots']
  187. # Make a prediction
  188. predictions = model.predict(testX[:1])
  189. label = labels[np.argmax(predictions)]
  190. print(label)
  191. plt.imshow(testX[:1][0])
  192. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement