'/content/fruit - JPG' 'No. of Pixels ' 'Shape '
'/content/fruit - JPG' 'No. of Pixels ' 'Shape '
'/content/fruit - JPG' 'No. of Pixels ' 'Shape '
a) Find the properties of the image such as size of the image, number of
pixels and channel in the image.
c) Split the image into a individual channel and display each channel image.
import numpy as np
import pandas as pd
import cv2 as cv
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img=cv.imread('/content/fruit.jpg')
cv2_imshow(img)
print('No. of Pixels '+ str(img.size))
print('shape '+ str(img.shape))
No. of Pixels186756
shape(197, 316, 3)
b,g,r=cv.split(img)
cv2_imshow(b)
cv2_imshow(g)
cv2_imshow(r)
(height,width)=img.shape[:2]
print(height)
print(width)
img_resize=cv.resize(img,(int(width/2),int(height/2)),interpolation=cv.INTER_
LINEAR)
cv2_imshow(img_resize)
img_resize=cv.resize(img,(int(width/2),int(height/2)),interpolation=cv.INTER_
CUBIC)
cv2_imshow(img_resize)
197
316
mat=cv.getRotationMatrix2D((int(width/2),int(height/2)),45,1)
img_rotate=cv.warpAffine(img,mat,(width,height))
cv2_imshow(img_rotate)
M=np.float32([[1,0,100],[0,1,50]])
img_translation=cv.warpAffine(img,M,(width,height))
cv2_imshow(img_translation)
img_neg=1-img
cv2_imshow(img_neg)
print("/n")
a=np.array(img.data)
b=a.max()
img_neg1=b-img
cv2_imshow(img_neg1)
/n
Question- a)Changing Image into HSV Format
b)Cropping an Image
c) Blurring an Image
import numpy as np
import matplotlib.pyplot as plt
import cv2
img=cv2.imread('/content/puppy.jpg')
hsv_image=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
plt.imshow(hsv_image)
<matplotlib.image.AxesImage at 0x7bc71c1df7c0>
img=cv2.imread('/content/puppy.jpg',cv2.IMREAD_UNCHANGED)
crop=img[10:420,30:420]
plt.imshow(crop)
<matplotlib.image.AxesImage at 0x7bc70e8e1ba0>
img_src=cv2.imread('/content/puppy.jpg')
img_rst=cv2.blur(img_src,(5,5))
cv2.imwrite('result.jpg',img_rst)
plt.imshow(img_rst)
<matplotlib.image.AxesImage at 0x7bc71cce1360>
img=cv2.imread('/content/puppy.jpg',cv2.IMREAD_UNCHANGED)
img_grey=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh=100
ret,thresh_img=cv2.threshold(img_grey,thresh,255,cv2.THRESH_BINARY)
contours,hierarchy=cv2.findContours(thresh_img,cv2.RETR_TREE,cv2.CHAIN_APPROX
_SIMPLE)
img_contours=np.zeros(img.shape)
cv2.drawContours(img_contours, contours, -1, (0,255,0),3)
cv2.imwrite('contours.png',img_contours)
plt.imshow(img_contours)
<matplotlib.image.AxesImage at 0x7bc70e8aef20>
img=cv2.imread('/content/puppy.jpg',cv2.IMREAD_UNCHANGED)
position=(10,50)
cv2.putText(img,"IT IS A
PUPPY",position,cv2.FONT_HERSHEY_SIMPLEX,1,(209,80,0,2))
cv2.imwrite('output.png',img)
plt.imshow(img)
<matplotlib.image.AxesImage at 0x7bc70ea6ccd0>
Experiment-3
import numpy as np
import cv2
import random
import matplotlib.pyplot as plt
img1=cv2.imread("/content/puppy.jpg",cv2.IMREAD_GRAYSCALE)
c=np.array(img1.data)
plt.subplot(2,5,1)
plt.title('ORIGINAL')
plt.imshow(c,cmap='gray')
<matplotlib.image.AxesImage at 0x7fb544e360e0>
img=cv2.imread('/content/puppy.jpg')
kernel=np.ones((3,3),np.float32)/9
dst=cv2.filter2D(img,-1, kernel)
cv2_imshow(img)
print("\n")
cv2_imshow(dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=cv2.imread('/content/puppy.jpg')
blur=cv2.blur(img,(5,5))
cv2_imshow(img)
print("\n")
cv2_imshow(blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=cv2.imread('/content/puppy.jpg')
blur=cv2.blur(img,(10,15))
cv2_imshow(img)
print("\n")
cv2_imshow(blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
import pandas as pd
img=cv2.imread('/content/puppy.jpg')
blur=cv2.GaussianBlur(img,(5,5),0)
cv2_imshow(img)
print("\n")
cv2_imshow(blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=cv2.imread('/content/puppy.jpg',cv2.IMREAD_GRAYSCALE)
plt.subplot(1,2,1)
plt.title('ORIGINAL')
plt.imshow(img, cmap='gray')
b=img.shape
contrastedImg=np.zeros((b[0],b[1]))
plt.subplot(1,2,2)
plt.title('Contrasted Stretched')
plt.imshow(contrastedImg, cmap='gray')
plt.show()
1. Median Filtering
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img=cv2.imread('/content/puppy.jpg')
median=cv2.medianBlur(img,5)
cv2_imshow(img)
print('/n')
cv2_imshow(median)
cv2.waitKey(0)
cv2.destroyAllWindows()
/n
2.Sharpening using kernels
img=cv2.imread('/content/puppy.jpg')
kernel_sharp1=np.array([[-1,-1,-1],[-1,9,-1],[-1,-1,-1]])
output1=cv2.filter2D(img,-1,kernel_sharp1)
cv2_imshow(output1)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=cv2.imread('/content/puppy.jpg')
kernel_sharp1=np.array([[1,1,1],[1,-7,1],[1,1,1]])
output1=cv2.filter2D(img,-1,kernel_sharp1)
cv2_imshow(output1)
cv2.waitKey(0)
cv2.destroyAllWindows()
3.Histogram Equalization
img=cv2.imread('/content/puppy.jpg',cv2.IMREAD_GRAYSCALE)
img=np.array(img)
flat=img.flatten()
plt.subplot(2,2,1)
plt.title('ORIGINAL HISTOGRAM')
plt.hist(flat,bins=50)
def get_histogram(image,bins):
histogram=np.zeros(bins)
for pixel in image:
histogram[pixel]+=1
return histogram
hist=get_histogram(flat,256)
plt.plot(hist)
def cumsum(a):
b=[a[0]]
for i in range(1,len(a)):
b.append(b[-1]+a[i])
return np.array(b)
cs=cumsum(hist)
nj=cs*255
N=cs.max()
cs=nj/N
plt.plot(cs)
img_new=cs[flat]
plt.subplot(2,2,2)
plt.title('EQUALIZED HISTOGRAM')
plt.hist(flat,bins=50)
img_new=np.reshape(img_new,img.shape)
plt.subplot(2,2,3)
plt.title('ORIGINAL IMAGE')
plt.imshow(img,cmap='gray')
plt.subplot(2,2,4)
plt.title('EQUALIZED IMAGE')
plt.imshow(img_new,cmap='gray')
plt.subplots_adjust(top=0.92,bottom=0.08,left=0.10,
right=0.95,hspace=0.50,wspace=0.92)
plt.show()
plt.subplot(1,3,1)
plt.title('ORIGINAL')
plt.imshow(img,cmap='gray')
sobelX=[[0 for i in range(img.shape[1])]for j in range(img.shape[0])]
sobelY=[[0 for i in range(img.shape[1])]for j in range(img.shape[0])]
prewittX=[[0 for i in range(img.shape[1])]for j in range(img.shape[0])]
prewittY=[[0 for i in range(img.shape[1])]for j in range(img.shape[0])]
laplacian=[[0 for i in range(img.shape[1])]for j in range(img.shape[0])]
img=np.pad(img, pad_width=1,mode='constant',constant_values=0)
sobelGx=[[-1,0,-1],[-2,0,2],[-1,0,1]]
sobelGy=[[-1,-2,-1],[0,0,0],[1,2,1]]
prewittGx=[[-1,0,1],[-1,0,1],[-1,0,1]]
prewittGy=[[-1,-1,-1],[0,0,0],[1,1,1]]
laplacianG=[[0,-1,0],[-1,4,-1],[0,-1,0]]
for i in range(img.shape[0]-2):
for j in range(img.shape[1]-2):
sobelX[i][j]=np.sum(np.multiply(sobelGx, img[i:i+3,j:j+3]))
sobelY[i][j]=np.sum(np.multiply(sobelGy, img[i:i+3,j:j+3]))
prewittX[i][j]=np.sum(np.multiply(prewittGx, img[i:i+3,j:j+3]))
prewittY[i][j]=np.sum(np.multiply(prewittGy, img[i:i+3,j:j+3]))
laplacian[i][j]=np.sum(np.multiply(laplacianG, img[i:i+3,j:j+3]))
plt.subplot(1,3,2)
plt.title('SOBEL Gx')
plt.imshow(sobelX,cmap='gray')
plt.subplot(1,3,3)
plt.title('SOBEL Gy')
plt.imshow(sobelY,cmap='gray')
plt.subplots_adjust(top=0.92,bottom=0.08,left=0.10,
right=0.95,hspace=0.50,wspace=0.92)
plt.show()
plt.subplot(1,3,1)
plt.title('ORIGINAL')
plt.imshow(img,cmap='gray')
plt.subplot(1,3,2)
plt.title('PREWITT Gx')
plt.imshow(prewittX,cmap='gray')
plt.subplot(1,3,3)
plt.title('PREWITT Gy')
plt.imshow(prewittY,cmap='gray')
plt.subplots_adjust(top=0.92,bottom=0.08,left=0.10,
right=0.95,hspace=0.50,wspace=0.92)
plt.show()
plt.subplot(1,2,1)
plt.title('ORIGINAL')
plt.imshow(img,cmap='gray')
plt.subplot(1,2,2)
plt.title('LAPLACIAN')
plt.imshow(laplacian,cmap='gray')
plt.subplots_adjust(top=0.92,bottom=0.08,left=0.10,
right=0.95,hspace=0.50,wspace=0.92)
plt.show()
Experiment-5
a. Erosion
b. Dilation
c. Opening
d. Closing
e. Morphological Gradient
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread("/content/puppy2.jpg",0)
kernel = np.ones((5,5), np.uint8)
erosion = cv2.erode(img, kernel, iterations=1)
cv2_imshow(erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread("/content/puppy2.jpg",0)
kernel = np.ones((5,5), np.uint8)
dilation = cv2.dilate(img, kernel, iterations=1)
cv2_imshow(dilation)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread("/content/puppy2.jpg",0)
kernel = np.ones((5,5), np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN, kernel)
cv2_imshow(opening)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread("/content/puppy2.jpg",0)
kernel = np.ones((5,5), np.uint8)
closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE, kernel)
cv2_imshow(closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread("/content/puppy2.jpg",0)
kernel = np.ones((5,5), np.uint8)
gradient = cv2.morphologyEx(img,cv2.MORPH_GRADIENT, kernel)
cv2_imshow(gradient)
cv2.waitKey(0)
cv2.destroyAllWindows()
Prepare a program for displaying all the types of image thresholding process:
cv2.THRESH_TOZERO; cv2.THRESH_TOZERO_INV.
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
image = cv2.imread("/content/biurd.jpg",0)
laplacian = cv2.Laplacian(image, cv2.CV_64F)
cv2_imshow(image)
print("\n")
cv2_imshow(laplacian)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread("/content/puppy2.jpg",0)
canny = cv2.Canny(img, 50, 240)
cv2_imshow(canny)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow
from skimage import io
from PIL import Image
import matplotlib.pyplot as plt
img1 = cv2.imread("/content/puppy2.jpg",0)
img2 = cv2.imread("/content/biurd.jpg",0)
ret,thresh1 = cv2.threshold(img1,127,255,cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img1,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img1,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img1,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img1,127,255,cv2.THRESH_TOZERO_INV)
ret,thresh6 = cv2.threshold(img2,127,255,cv2.THRESH_BINARY)
ret,thresh7 = cv2.threshold(img2,127,255,cv2.THRESH_BINARY_INV)
ret,thresh8 = cv2.threshold(img2,127,255,cv2.THRESH_TRUNC)
ret,thresh9 = cv2.threshold(img2,127,255,cv2.THRESH_TOZERO)
ret,thresh10 = cv2.threshold(img2,127,255,cv2.THRESH_TOZERO_INV)
for i in range(12):
plt.subplot(3, 4, i+1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
Experiment-6
1. Write the programs to display the use of Prewitt Operator for edge
detection using OpenCV.
a. Global thresholding
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow # for image display
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread('pikachu.jpg')
cv2_imshow(img)
print("\n")
cv2_imshow(img_prewittx)
print("\n")
cv2_imshow(img_prewitty)
print("\n")
cv2_imshow(img_prewittx + img_prewitty)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow # for image display
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread('pikachu.jpg')
cv2_imshow(img)
cv2_imshow(img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import pandas as pd
import cv2
from google.colab.patches import cv2_imshow # for image display
from skimage import io
from PIL import Image
import matplotlib.pylab as plt
img = cv2.imread('pikachu.jpg',0)
img = cv2.medianBlur(img, 5)
plt.show()
#EXP 7
import numpy as np
import matplotlib.pyplot as plt
import cv2
%matplotlib inline
image = cv2.imread('pikachu.jpg')
# Reshaping the image into a 2D array of pixels and 3 color values (RGB)
pixel_vals = image.reshape((-1, 3))
plt.imshow(segmented_image)
plt.show()
import cv2
import numpy as np
img = cv2.imread('pikachu.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
cv2.imwrite('/content/houghlines.jpg', img)
output = cv2.imread('houghlines.jpg')
cv2_imshow(output)
cv2.waitKey(0)
cv2.destroyAllWindows()
Experiment-7
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.feature import canny
coins = data.coins()
hist, _ = np.histogram(coins, bins=np.arange(0, 256))
fig, ax1 = plt.subplots()
ax1.imshow(coins, cmap=plt.cm.gray, interpolation='nearest')
edges = canny(coins/255.)
fig, ax2 = plt.subplots(figsize=(4, 3))
ax2.imshow(edges, cmap=plt.cm.gray, interpolation='nearest')
ax2.axis('off')
ax2.set_title('Canny detector')
plt.show()
from scipy import ndimage as ndi
import matplotlib.pyplot as plt
from skimage import data
from skimage.feature import canny
coins = data.coins()
edges = canny(coins/255.)
fill_coins = ndi.binary_fill_holes(edges)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(fill_coins, cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
ax.set_title('Filling the holes')
plt.show()
coins = data.coins()
elevation_map = sobel(coins)
#resizing image
resized_img = resize(img, (128, 64))
imshow(resized_img)
print(resized_img.shape)
(182, 182, 3)
(128, 64, 3)
Experiment-8
1. Write a program for face detection using Haar Cascade Library.
import cv2
import numpy as np
%matplotlib inline
from matplotlib import pyplot as plt
import pylab
pylab.rcParams['figure.figsize']=(10.0,8.0)
base_image=cv2.imread("/content/NASA_Astronaut_Group_15.jpg")
grey=cv2.cvtColor(base_image,cv2.COLOR_BGR2GRAY)
plt.imshow(cv2.cvtColor(base_image, cv2.COLOR_BGR2RGB))
<matplotlib.image.AxesImage at 0x7f59fe3162f0>
<matplotlib.image.AxesImage at 0x7f5a10c983a0>
import cv2
import numpy as np
import pandas as pd
from google.colab.patches import cv2_imshow # for image display
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
"haarcascade_frontalface_default.xml")
img = cv2.imread("/content/NASA_Astronaut_Group_15.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
for x, y, w, h in faces:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
plots[1].set_title("Testing Image")
plots[1].imshow(test_image)
<matplotlib.image.AxesImage at 0x7f5a10ac9f60>
keypoints_without_size = np.copy(training_image)
keypoints_with_size = np.copy(training_image)
plt.subplot(1,2,1)
plt.title("Train keypoints With Size")
plt.imshow(keypoints_with_size, cmap='Reds')
plt.subplot(1,2,2)
plt.title("Train keypoints Without Size")
plt.imshow(keypoints_without_size, cmap='Reds')
# Perform the matching between the SIFT descriptors of the Training image and
the test image
matches = bf.match(train_descriptor, test_descriptor)
# The matches with shorter distance are The Ones we want.
matches = sorted(matches, key=lambda x: x.distance)
# Print total number of matching points between the training and query images
print("\nNumber of Matching Keypoints Between The Training and Query Images:
", len(matches))
Number of Matching Keypoints Between The Training and Query Images: 6579
url = "https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data"
# Loading dataset into Pandas DataFrame
df = pd.read_csv(url, names=['sepal length', 'sepal width', 'petal length',
'petal width', 'target'])
df.head()
features
y = df.loc[:, ["target"]].values
x = StandardScaler().fit_transform(x)
pd.DataFrame(data=x, columns=features).head()
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
principaldf = pd.DataFrame(data=principalComponents, columns=['principal
component 1', 'principal component 2'])
principaldf.head()
df['target'].head()
0 Iris-setosa
1 Iris-setosa
2 Iris-setosa
3 Iris-setosa
4 Iris-setosa
Name: target, dtype: object
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_title('Principal Component Analysis', fontsize=15)
ax.set_xlabel("Principal Component 1", fontsize=15)
ax.set_ylabel("Principal Component 2", fontsize=15)
dataset.head()
X = dataset.loc[:, 'Class']
y = dataset['Class']
# Now, X_train contains the principal components, and y_train contains the
class labels
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(max_depth=2, random_state=0)
classifier.fit(X_train, y_train)
cm = confusion_matrix(y_test, y_pred)
print(cm)
[[5 0 0]
[0 3 3]
[0 0 4]]
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
pca = PCA()
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
explained_variance_ratio = pca.explained_variance_ratio_
pea = PCA(n_components=1)
X_train = pea.fit_transform(X_train)
X_test = pea.transform(X_test)
from sklearn.ensemble import RandomForestClassifier
cm = confusion_matrix(y_test, y_pred)
print(cm)
[[1 0 4]
[2 0 4]
[0 0 4]]
# converting the Image data into values of pixels, i.e. - image of dimension
28 X 28 to single row of 784 pixels (28x28 = 784).
print("Dimension of training data before reshaping:", train_X.shape)
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 784)] 0
dense (Dense) (None, 2000) 1570000
=================================================================
Total params: 5652794 (21.56 MB)
Trainable params: 5652794 (21.56 MB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
Epoch 1/108
30/30 [==============================] - 60s 2s/step - loss: 0.0901 -
val_loss: 0.0671
Epoch 2/108
30/30 [==============================] - 38s 1s/step - loss: 0.0556 -
val_loss: 0.0449
Epoch 3/108
30/30 [==============================] - 38s 1s/step - loss: 0.0412 -
val_loss: 0.0386
Epoch 4/108
30/30 [==============================] - 40s 1s/step - loss: 0.0368 -
val_loss: 0.0353
Epoch 5/108
30/30 [==============================] - 38s 1s/step - loss: 0.0338 -
val_loss: 0.0315
Epoch 6/108
30/30 [==============================] - 37s 1s/step - loss: 0.0298 -
val_loss: 0.0280
Epoch 7/108
30/30 [==============================] - 37s 1s/step - loss: 0.0269 -
val_loss: 0.0259
Epoch 8/108
30/30 [==============================] - 39s 1s/step - loss: 0.0251 -
val_loss: 0.0246
Epoch 9/108
30/30 [==============================] - 37s 1s/step - loss: 0.0238 -
val_loss: 0.0231
Epoch 10/108
30/30 [==============================] - 37s 1s/step - loss: 0.0227 -
val_loss: 0.0221
Epoch 11/108
30/30 [==============================] - 37s 1s/step - loss: 0.0224 -
val_loss: 0.0213
Epoch 12/108
30/30 [==============================] - 36s 1s/step - loss: 0.0208 -
val_loss: 0.0230
Epoch 13/108
30/30 [==============================] - 37s 1s/step - loss: 0.0206 -
val_loss: 0.0199
Epoch 14/108
30/30 [==============================] - 37s 1s/step - loss: 0.0196 -
val_loss: 0.0193
Epoch 15/108
30/30 [==============================] - 38s 1s/step - loss: 0.0191 -
val_loss: 0.0189
Epoch 16/108
30/30 [==============================] - 41s 1s/step - loss: 0.0185 -
val_loss: 0.0185
Epoch 17/108
30/30 [==============================] - 38s 1s/step - loss: 0.0179 -
val_loss: 0.0183
Epoch 18/108
30/30 [==============================] - 38s 1s/step - loss: 0.0181 -
val_loss: 0.0173
Epoch 19/108
30/30 [==============================] - 37s 1s/step - loss: 0.0170 -
val_loss: 0.0169
Epoch 20/108
30/30 [==============================] - 36s 1s/step - loss: 0.0167 -
val_loss: 0.0167
Epoch 21/108
30/30 [==============================] - 37s 1s/step - loss: 0.0166 -
val_loss: 0.0163
Epoch 22/108
30/30 [==============================] - 37s 1s/step - loss: 0.0162 -
val_loss: 0.0162
Epoch 23/108
30/30 [==============================] - 37s 1s/step - loss: 0.0159 -
val_loss: 0.0159
Epoch 24/108
30/30 [==============================] - 40s 1s/step - loss: 0.0157 -
val_loss: 0.0157
Epoch 25/108
30/30 [==============================] - 37s 1s/step - loss: 0.0154 -
val_loss: 0.0153
Epoch 26/108
30/30 [==============================] - 37s 1s/step - loss: 0.0155 -
val_loss: 0.0153
Epoch 27/108
30/30 [==============================] - 37s 1s/step - loss: 0.0152 -
val_loss: 0.0156
Epoch 28/108
30/30 [==============================] - 37s 1s/step - loss: 0.0149 -
val_loss: 0.0150
Epoch 29/108
30/30 [==============================] - 37s 1s/step - loss: 0.0147 -
val_loss: 0.0148
Epoch 30/108
30/30 [==============================] - 37s 1s/step - loss: 0.0146 -
val_loss: 0.0147
Epoch 31/108
30/30 [==============================] - 36s 1s/step - loss: 0.0149 -
val_loss: 0.0145
Epoch 32/108
30/30 [==============================] - 36s 1s/step - loss: 0.0142 -
val_loss: 0.0145
Epoch 33/108
30/30 [==============================] - 38s 1s/step - loss: 0.0142 -
val_loss: 0.0145
Epoch 34/108
30/30 [==============================] - 37s 1s/step - loss: 0.0142 -
val_loss: 0.0143
Epoch 35/108
30/30 [==============================] - 37s 1s/step - loss: 0.0141 -
val_loss: 0.0144
Epoch 36/108
30/30 [==============================] - 36s 1s/step - loss: 0.0139 -
val_loss: 0.0140
Epoch 37/108
30/30 [==============================] - 36s 1s/step - loss: 0.0138 -
val_loss: 0.0139
Epoch 38/108
30/30 [==============================] - 37s 1s/step - loss: 0.0140 -
val_loss: 0.0140
Epoch 39/108
30/30 [==============================] - 37s 1s/step - loss: 0.0136 -
val_loss: 0.0138
Epoch 40/108
30/30 [==============================] - 37s 1s/step - loss: 0.0136 -
val_loss: 0.0140
Epoch 41/108
30/30 [==============================] - 38s 1s/step - loss: 0.0135 -
val_loss: 0.0138
Epoch 42/108
30/30 [==============================] - 35s 1s/step - loss: 0.0134 -
val_loss: 0.0137
Epoch 43/108
30/30 [==============================] - 37s 1s/step - loss: 0.0134 -
val_loss: 0.0139
Epoch 44/108
30/30 [==============================] - 37s 1s/step - loss: 0.0132 -
val_loss: 0.0134
Epoch 45/108
30/30 [==============================] - 37s 1s/step - loss: 0.0134 -
val_loss: 0.0136
Epoch 46/108
30/30 [==============================] - 39s 1s/step - loss: 0.0131 -
val_loss: 0.0135
Epoch 47/108
30/30 [==============================] - 37s 1s/step - loss: 0.0133 -
val_loss: 0.0134
Epoch 48/108
30/30 [==============================] - 35s 1s/step - loss: 0.0129 -
val_loss: 0.0134
Epoch 49/108
30/30 [==============================] - 37s 1s/step - loss: 0.0131 -
val_loss: 0.0132
Epoch 50/108
30/30 [==============================] - 38s 1s/step - loss: 0.0129 -
val_loss: 0.0132
Epoch 51/108
30/30 [==============================] - 37s 1s/step - loss: 0.0128 -
val_loss: 0.0133
Epoch 52/108
30/30 [==============================] - 37s 1s/step - loss: 0.0129 -
val_loss: 0.0130
Epoch 53/108
30/30 [==============================] - 40s 1s/step - loss: 0.0127 -
val_loss: 0.0135
Epoch 54/108
30/30 [==============================] - 38s 1s/step - loss: 0.0128 -
val_loss: 0.0129
Epoch 55/108
30/30 [==============================] - 36s 1s/step - loss: 0.0126 -
val_loss: 0.0130
Epoch 56/108
30/30 [==============================] - 37s 1s/step - loss: 0.0126 -
val_loss: 0.0132
Epoch 57/108
30/30 [==============================] - 38s 1s/step - loss: 0.0125 -
val_loss: 0.0141
Epoch 58/108
30/30 [==============================] - 39s 1s/step - loss: 0.0128 -
val_loss: 0.0128
Epoch 59/108
30/30 [==============================] - 38s 1s/step - loss: 0.0124 -
val_loss: 0.0129
Epoch 60/108
30/30 [==============================] - 38s 1s/step - loss: 0.0123 -
val_loss: 0.0129
Epoch 61/108
30/30 [==============================] - 38s 1s/step - loss: 0.0124 -
val_loss: 0.0127
Epoch 62/108
30/30 [==============================] - 38s 1s/step - loss: 0.0123 -
val_loss: 0.0127
Epoch 63/108
30/30 [==============================] - 37s 1s/step - loss: 0.0123 -
val_loss: 0.0126
Epoch 64/108
30/30 [==============================] - 38s 1s/step - loss: 0.0123 -
val_loss: 0.0129
Epoch 65/108
30/30 [==============================] - 38s 1s/step - loss: 0.0122 -
val_loss: 0.0125
Epoch 66/108
30/30 [==============================] - 39s 1s/step - loss: 0.0122 -
val_loss: 0.0128
Epoch 67/108
30/30 [==============================] - 38s 1s/step - loss: 0.0121 -
val_loss: 0.0125
Epoch 68/108
30/30 [==============================] - 38s 1s/step - loss: 0.0121 -
val_loss: 0.0125
Epoch 69/108
30/30 [==============================] - 38s 1s/step - loss: 0.0120 -
val_loss: 0.0125
Epoch 70/108
30/30 [==============================] - 37s 1s/step - loss: 0.0119 -
val_loss: 0.0127
Epoch 71/108
30/30 [==============================] - 37s 1s/step - loss: 0.0122 -
val_loss: 0.0124
Epoch 72/108
30/30 [==============================] - 38s 1s/step - loss: 0.0118 -
val_loss: 0.0124
Epoch 73/108
30/30 [==============================] - 38s 1s/step - loss: 0.0119 -
val_loss: 0.0125
Epoch 74/108
30/30 [==============================] - 38s 1s/step - loss: 0.0118 -
val_loss: 0.0124
Epoch 75/108
30/30 [==============================] - 39s 1s/step - loss: 0.0118 -
val_loss: 0.0123
Epoch 76/108
30/30 [==============================] - 38s 1s/step - loss: 0.0118 -
val_loss: 0.0122
Epoch 77/108
30/30 [==============================] - 37s 1s/step - loss: 0.0118 -
val_loss: 0.0123
Epoch 78/108
30/30 [==============================] - 37s 1s/step - loss: 0.0117 -
val_loss: 0.0123
Epoch 79/108
30/30 [==============================] - 38s 1s/step - loss: 0.0116 -
val_loss: 0.0122
Epoch 80/108
30/30 [==============================] - 37s 1s/step - loss: 0.0119 -
val_loss: 0.0123
Epoch 81/108
30/30 [==============================] - 38s 1s/step - loss: 0.0116 -
val_loss: 0.0121
Epoch 82/108
30/30 [==============================] - 38s 1s/step - loss: 0.0115 -
val_loss: 0.0123
Epoch 83/108
30/30 [==============================] - 39s 1s/step - loss: 0.0116 -
val_loss: 0.0121
Epoch 84/108
30/30 [==============================] - 40s 1s/step - loss: 0.0116 -
val_loss: 0.0121
Epoch 85/108
30/30 [==============================] - 38s 1s/step - loss: 0.0114 -
val_loss: 0.0120
Epoch 86/108
30/30 [==============================] - 37s 1s/step - loss: 0.0115 -
val_loss: 0.0120
Epoch 87/108
30/30 [==============================] - 38s 1s/step - loss: 0.0114 -
val_loss: 0.0124
Epoch 88/108
30/30 [==============================] - 38s 1s/step - loss: 0.0116 -
val_loss: 0.0120
Epoch 89/108
30/30 [==============================] - 38s 1s/step - loss: 0.0113 -
val_loss: 0.0121
Epoch 90/108
30/30 [==============================] - 38s 1s/step - loss: 0.0113 -
val_loss: 0.0122
Epoch 91/108
30/30 [==============================] - 39s 1s/step - loss: 0.0114 -
val_loss: 0.0120
Epoch 92/108
30/30 [==============================] - 37s 1s/step - loss: 0.0113 -
val_loss: 0.0120
Epoch 93/108
30/30 [==============================] - 37s 1s/step - loss: 0.0112 -
val_loss: 0.0119
Epoch 94/108
30/30 [==============================] - 38s 1s/step - loss: 0.0114 -
val_loss: 0.0120
Epoch 95/108
30/30 [==============================] - 38s 1s/step - loss: 0.0112 -
val_loss: 0.0118
Epoch 96/108
30/30 [==============================] - 38s 1s/step - loss: 0.0114 -
val_loss: 0.0119
Epoch 97/108
30/30 [==============================] - 38s 1s/step - loss: 0.0111 -
val_loss: 0.0118
Epoch 98/108
30/30 [==============================] - 38s 1s/step - loss: 0.0111 -
val_loss: 0.0120
Epoch 99/108
30/30 [==============================] - 37s 1s/step - loss: 0.0113 -
val_loss: 0.0118
Epoch 100/108
30/30 [==============================] - 38s 1s/step - loss: 0.0111 -
val_loss: 0.0118
Epoch 101/108
30/30 [==============================] - 38s 1s/step - loss: 0.0110 -
val_loss: 0.0118
Epoch 102/108
30/30 [==============================] - 38s 1s/step - loss: 0.0112 -
val_loss: 0.0119
Epoch 103/108
30/30 [==============================] - 38s 1s/step - loss: 0.0110 -
val_loss: 0.0118
Epoch 104/108
30/30 [==============================] - 38s 1s/step - loss: 0.0110 -
val_loss: 0.0124
Epoch 105/108
30/30 [==============================] - 37s 1s/step - loss: 0.0112 -
val_loss: 0.0117
Epoch 106/108
30/30 [==============================] - 37s 1s/step - loss: 0.0110 -
val_loss: 0.0118
Epoch 107/108
30/30 [==============================] - 38s 1s/step - loss: 0.0110 -
val_loss: 0.0122
Epoch 108/108
30/30 [==============================] - 37s 1s/step - loss: 0.0111 -
val_loss: 0.0117
To predict images
# to predict the reconstructed images for the original images...
pred = autoencoder.predict(val_X)
# Loading data
irisData = load_iris()
knn = KNeighborsClassifier(n_neighbors=7)
knn.fit(X_train, y_train)
[1 0 2 1 1 0 1 2 2 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0]
# Loading data
irisData = load_iris()
knn = KNeighborsClassifier(n_neighbors=7)
knn.fit(X_train, y_train)
# Calculate the accuracy of the model
print(knn.score(X_test, y_test))
0.9666666666666667
irisData = load_iris()
neighbors = np.arange(1, 9)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
plt.legend()
plt.xlabel('n_neighbors')
plt.ylabel('Accuracy')
plt.show()
from sklearn.datasets import make_blobs
X, Y = make_blobs(n_samples=500, centers=2,
random_state=0, cluster_std=0.42)
# plotting scatters
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# plotting scatter
plt.scatter(X[:, 0], X[:, 1], c=Y, s=50, cmap="spring")
plt.xlim(-1, 3.5)
plt.show()
2) Write a program to implement SVM: Maximum margin for separating hyperplane.
import numpy as np
import matplotlib.pyplot as plt
x_lin = ax.get_xlim()
y_lin = ax.get_ylim()
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = clf.decision_function(xy).reshape(XX.shape)
<matplotlib.collections.PathCollection at 0x7898df325840>
%matplotlib inline
bankdata = pd.read_csv("bill_authentication.csv")
bankdata.shape
bankdata.head()
X = bankdata.drop('Class', axis=1)
y = bankdata['Class']
SVC(kernel='linear')
y_pred = svclassifier.predict(X_test)
[[147 2]
[ 2 124]]
precision recall f1-score support
import pandas as pd
url = "https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data"
# Assign column names to the dataset
X = irisdata.drop('Class', axis=1)
y = irisdata['Class']
Gaussian Kernel
from sklearn.svm import SVC
svclassifier = SVC(kernel='rbf')
svclassifier.fit(X_train,y_train)
SVC()
y_pred=svclassifier.predict(X_test)
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
[[ 8 0 0]
[ 0 15 0]
[ 0 0 7]]
precision recall f1-score support
accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
Sigmoidal Kernel
from sklearn.svm import SVC
svclassifier = SVC(kernel='sigmoid')
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)
[[ 0 0 8]
[ 0 0 15]
[ 0 0 7]]
precision recall f1-score support
accuracy 0.23 30
macro avg 0.08 0.33 0.13 30
weighted avg 0.05 0.23 0.09 30
/usr/local/lib/python3.10/dist-
packages/sklearn/metrics/_classification.py:1344: UndefinedMetricWarning:
Precision and F-score are ill-defined and being set to 0.0 in labels with no
predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, msg_start, len(result))
/usr/local/lib/python3.10/dist-
packages/sklearn/metrics/_classification.py:1344: UndefinedMetricWarning:
Precision and F-score are ill-defined and being set to 0.0 in labels with no
predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, msg_start, len(result))
/usr/local/lib/python3.10/dist-
packages/sklearn/metrics/_classification.py:1344: UndefinedMetricWarning:
Precision and F-score are ill-defined and being set to 0.0 in labels with no
predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, msg_start, len(result))