-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_8_dhruvdhayal_ai_ml.py
578 lines (463 loc) · 17.6 KB
/
day_8_dhruvdhayal_ai_ml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# -*- coding: utf-8 -*-
"""Day-8_DHRUVDHAYAL_AI/ML.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1BEFVacg39ucrMuyML9YoRmfDijTYsOyI
#k-MEANS CLASSIFICATIONS.
"""
#Now, we have to perform the K-Means Classifications.
#Importing all the Inbuilt Libraries.
from sklearn import svm;
from sklearn import metrics;
from sklearn import model_selection;
from sklearn import cluster;
#Importing commonly used Libraries.
import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
import matplotlib.image as mimg;
#Now, we have to import the random datasets.
data=np.random.randint(0,100,(500,2));
print("\n 1. Total Length of the Data Given: ",data.shape);
print("\n");
#Now, we have to visualise the data in graphical forms.
plt.figure(1,figsize=(4,4));
plt.scatter(data[:,0],data[:,1]);
plt.title("Raw Data");
plt.show();
"""#Experiment: 1.
--> On, K-Means Clustering .
--> Importing all the Libraries and datsets randomly and show them with the scatter graph forms!
"""
#Importing all the Machine Learning Libraries.
from sklearn import datasets;
from sklearn import svm;
from sklearn import metrics;
from sklearn import model_selection;
from sklearn import cluster;
#Importing the Common Based Libraries.
import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
import matplotlib.image as mimg;
#Now, we have to put the random datsets values.
data=np.random.randint(0,100,(500,2));
print("\n 1. Total Length of the Given Data: ",data.shape);
print("\n");
#Now, we have to visualise the values of the Data.
plt.figure(1,figsize=(4,4));
plt.scatter(data[:,0],data[:,1]);
plt.title("Raw Data");
plt.show();
"""#Now, we have to train the Model by Unsupervised Learning."""
#Experimenting the K-Means Unsupervised Learning Model.
#To, segment the 2-D Model.
#Creating the K-Means Model.
km_model=cluster.KMeans(n_clusters=4,random_state=5);
#Now, we have to train the Model.
km_model=km_model.fit(data);
#No, labels are present hence simply show the Values.
print("\n 1. Centers of the Clusters are given here: \n\n",km_model.cluster_centers_);
print("\n 2. Total Number of the Labels available are: ",len(km_model.labels_));
#print(len(km_model.labels_));
print("\n 3. Centers coordinates along the X-Axes: ",km_model.cluster_centers_[0][0]);
#Now, we have to visualise the Model to show in the Graphical forms!
plt.figure(1,figsize=(8,4));
plt.subplot(1,2,1);
plt.scatter(data[:,0],data[:,1]);
plt.title("Raw Data");
#Now, we have to show the clustering by classification using the K-Means.
plt.subplot(1,2,2);
plt.scatter(data[:,0],data[:,1],c=km_model.labels_);
plt.title("K-Means Clustering");
for i in range(len(km_model.cluster_centers_)):
dx=km_model.cluster_centers_[i][0];
dy=km_model.cluster_centers_[i][1];
plt.plot(dx,dy,'kd');
plt.show();
"""#Elbow Methods.
--> Elbow Methods(Inertia): The Sum of the Squared Distances, totally when the total number of Iterations, gives you the smalles and optimal values, when after the Iteration the smallest values is schieved and we did not get any optimal value during the further iterations then we take the finall optimum values properly!
"""
#Using of the Elbow Methods.
#Inertia: Sum of the Squared Distances to find the best smallest optimum values during the Multiple Iterations.
dist=[];
k_values=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; #We, also uses k_values = range(1,16);
for i in range(len(k_values)):
km_model=cluster.KMeans(n_clusters=k_values[i],random_state=5);
#Now, we have to train the Model.
km_model=km_model.fit(data);
#Now, append the list items.
dist.append(km_model.inertia_);
"""#Visualise the values of the Elbow Methods."""
#Visualise the Values of the Elbow Methods.
plt.figure(1,figsize=(8,4));
plt.plot(k_values,dist,'--kd');
plt.title("Elbow Methods");
plt.xlabel("K-Values");
plt.ylabel("Sum of the Squared Distances");
plt.grid("on");
plt.show();
"""#Practicing the Values on the K-Means Clustering by using the given below!
--> By, using the Training Model.
--> By, using the 'Elbow Methods'.
"""
#Importing all the Previos Sklearn Libraries.
from sklearn import datasets;
from sklearn import svm;
from sklearn import metrics;
from sklearn import model_selection;
from sklearn import cluster;
#Inbuilt the pre-defined values of the Libraries.
import numpy as np;
import pandas as pd
import matplotlib.pyplot as plt;
import matplotlib.image as mimg;
#Importing the Random data sets values.
data=np.random.randint(0,100,(500,2));
print("\n 1. Total Length of the Data are: ",data.shape);
print("\n");
#Now, we have to visualise the data randomly!
plt.figure(1,figsize=(4,4));
plt.scatter(data[:,0],data[:,1]);
plt.title("Raw Data");
plt.show();
#Now, we have to train the Model.
#Proper classifications in the K-Means Clusttering.
km_model=cluster.KMeans(n_clusters=4,random_state=5);
#Train the Model to become the Trained Datasets Models.
km_model=km_model.fit(data);
#No, labels present hence we have to print the values.
print("\n 1. Center of the Clusterring are given here: \n\n",km_model.cluster_centers_);
print("\n 2. Total Number of the Labels are: ",len(km_model.labels_));
#print(km_model.labels_);
print("\n 3. Now, we have to show the centroids in the Graphical forms! ",km_model.cluster_centers_[0][0]);
#Now, we need to visualise the Model to show the values.
plt.figure(1,figsize=(8,4));
plt.subplot(1,2,1);
plt.scatter(data[:,0],data[:,1]);
plt.title("Raw Data");
#Now, we have to show the Output of K-Means Clusterring!
plt.subplot(1,2,2);
plt.scatter(data[:,0],data[:,1],c=km_model.labels_);
plt.title("K-Means Clusterring");
for i in range(len(km_model.cluster_centers_)):
dx=km_model.cluster_centers_[i][0];
dy=km_model.cluster_centers_[i][1];
plt.plot(dx,dy,'kd');
#Show the Values Finally!
plt.show();
#By, using the Elbow Methods.
#Now, using level of the Inertia.
#Inertia: sum of the squared distances and getting the best optimal values after several iteration when it stops at certain values and cannot reduce the values after many iterations, it means that value is found to be 'Best Optimal Values'.
dist=[];
k_values=range(1,16);
for i in range(len(k_values)):
km_model=cluster.KMeans(n_clusters=k_values[i],random_state=5);
#Training The Model given here!
km_model=km_model.fit(data);
#Append the items in the given list.
dist.append(km_model.inertia_);
#Now, we have to visualise the Data.
plt.figure(1,figsize=(8,4));
plt.plot(k_values,dist,'--kd');
plt.title("Elbow Methods");
plt.xlabel("K-Values");
plt.ylabel("Sum of the Squared Distances");
plt.grid("on");
plt.show();
"""#Experimentation: 2
--> We, have to perform K-Means Clusterring in the given Mall_Customers .CSV Files.
"""
#Importing all the Libraries.
#from sklearn import datsets;
from sklearn import svm;
from sklearn import metrics;
from sklearn import model_selection;
from sklearn import cluster;
#Importing the Normal File Pre-Defined Libraries.
import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
import matplotlib.image as mimg;
#Now, we have to import the Values / or we also import files by using the google Mount.
path='/content/Mall_Customers(Practice).csv';
data=pd.read_csv(path);
#Now, we have to show all the Values!
print("\n 1. Total Length of the Given .CSV Files Data: ",data.shape);
print("\n-----------------------------------------------------------------\n");
print("\n 2. Complete Datasets present called given below: \n\n",data);
print("\n-----------------------------------------------------------------\n");
"""#Data Informations in the Given Mall_Customers.CSV"""
print(data.info());
"""#Description of the Data Values in the Given Files."""
print(data.describe());
"""#Using the Elbow Methods."""
#Now, we have to show the relationship data between 'Annual Income (k$)' and 'Spending Score (1-100)'
import matplotlib.pyplot as plt;
dx=data['Annual Income (k$)'];
dy=data['Spending Score (1-100)'];
plt.scatter(dx,dy);
plt.title("Raw Data Available");
plt.xlabel("Annual Income (k$)");
plt.ylabel("Spending Score (1-100)");
numarray1=np.array((dx,dy)).T;
print("\n --> Total Length of the Array given are: ",numarray1.shape);
print("\n");
plt.show();
#Using the Values of the Elbow Methods.
dist=[];
k_values=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
for i in range(len(k_values)):
km_model=cluster.KMeans(n_clusters=k_values[i],random_state=5);
#Now, we have to train the values of the Models.
km_model=km_model.fit(numarray1);
#Appending the items in the given Lists.
dist.append(km_model.inertia_);
#Now, I want to visualise the files of the Given Data.
plt.figure(1,figsize=(8,4));
plt.plot(k_values,dist,'--kd');
plt.title("Elbow Methods");
plt.xlabel("K-Values");
plt.ylabel("Sum of the Squared Distances");
plt.grid("on");
plt.show();
#Now, we have to train the model based on unsupervised Learning.
#Classification of the given Model.
km_model=cluster.KMeans(n_clusters=4,random_state=5);
#Training the Given Model.
km_model=km_model.fit(numarray1);
#Showing all values no-labels are present here!
print("\n 1. Center of the Clusterring are given here: \n\n",km_model.cluster_centers_);
print("\n 2. Total Number of the Labels are: ",len(km_model.labels_));
#print(km_model.labels_);
print("\n 3. Now, we have to show the centroids in the Graphical forms! ",km_model.cluster_centers_[0][0]);
#Now, we have to visualise the model data.
plt.figure(1,figsize=(8,4));
plt.subplot(1,2,1);
plt.scatter(numarray1[:,0],numarray1[:,1]);
plt.title("Raw Data");
#Now, showing the K-Means form of the Clusterring!
plt.subplot(1,2,2);
plt.scatter(numarray1[:,0],numarray1[:,1],c=km_model.labels_);
plt.title("K-Means Cluaterring");
for i in range(len(km_model.cluster_centers_)):
dx=km_model.cluster_centers_[i][0];
dy=km_model.cluster_centers_[i][1];
plt.plot(dx,dy,'kd');
#Now, plot the graph based on it and show them!
plt.show();
"""#Image Recognizations."""
#Importing the Inbuilt Libraries.
import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
import matplotlib.image as mimg;
#Now, we have to read the Image Data Files.
path='/content/Flower.jpeg';
data=mimg.imread(path);
#Now, we have to show the values of the Data.
print("\n --> Total Length of the Image Data are given here: ",data.shape);
print("\n");
#Now, we have to visualise our image data.
plt.figure(1,figsize=(4,4));
plt.imshow(data);
plt.title("Image Data");
plt.axis("off");
plt.show();
import cv2;
newimg=cv2.resize(data,(200,200));
print("\n --> Total Length of the New_Image are: ",newimg.shape);
print("\n");
#Visualise the Values of the Image Data.
plt.figure(1,figsize=(8,4));
plt.imshow(newimg);
plt.axis("off");
plt.show();
from google.colab.patches import cv2_imshow;
#Creating the Valuable Components whose range lie in (0-255)!
red=newimg[:,:,0]; #Creating the First Component.
green=newimg[:,:,1]; #Creating the Second Component.
blue=newimg[:,:,2]; #Creating the Third Component.
#Showing all the Components in the form of the Patches.
cv2_imshow(red);
cv2_imshow(green);
cv2_imshow(blue);
#Creating the three images numpy array to store the given values.
#Values of about uint8 types.
rIM=np.zeros((newimg.shape[0],newimg.shape[1],newimg.shape[2]),dtype='uint8');
gIM=np.zeros((newimg.shape[0],newimg.shape[1],newimg.shape[2]),dtype='uint8');
bIM=np.zeros((newimg.shape[0],newimg.shape[1],newimg.shape[2]),dtype='uint8');
#For testing.
print(rIM.shape);
#Now, we have to replace the values with each Components.
rIM[:,:,0]=red;
#Replacing it with the green components.
gIM[:,:,1]=green;
#Replacing it with the blue components.
bIM[:,:,2]=blue;
#Showing each and every components.
cv2_imshow(rIM);
cv2_imshow(gIM);
cv2_imshow(bIM);
"""#POINTS-TO-BE-REMEMBER.
-->You, have notice that we print the colors randomly but it prints the color in the form of 'bgr' , if we print the color in 'rgb' from automatically by default it return values in 'bgr' form of output.
--> Each Image Comes and lie's it in the given range from (0-255)!
"""
#Printing the Maximum values of each and every image Components.
print("(",rIM.min()," - ",rIM.max(),")");
print("(",gIM.min()," - ",gIM.max(),")");
print("(",bIM.min()," - ",bIM.max(),")");
"""#FACIAL RECOGNIZATIONS.
#Voila Jones - Algorithm used because it's effectively detect then no: of faces in the given images!
"""
# 1. First We, have to detect the Complete Images.
# 2. We, have to detect the Faces in the given Image.
# 3. Seperate it out!
#Importing all the pre-defined and inbuilt Libraries.
!pip install opencv-python;
#Importing all the pre-defined and inbuilt Libraries.
import cv2;
import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
import matplotlib.image as mimg;
from google.colab.patches import cv2_imshow
#Importing the Valuable Images path.
path='/content/office work.jpg';
data=cv2.imread(path);
new_im=cv2.resize(data,(512,512));
print("\n --> Total Length of the NewImage: ",new_im.shape);
#cv2.imshow("Multi faces image", im) # Replace with cv2_imshow if needed.
#Convert the color "BGR" it into the Gray Scale.
gray_im=cv2.cvtColor(new_im,cv2.COLOR_BGR2GRAY); # Change CV2 to cv2
print("\n --> Resolution of the gray image!")
print("\n",gray_im.shape)
#cv2.imshow("Multi faces image", gray_im) # Replace with cv2_imshow if needed.
path = "/content/haarcascade_frontalface_default (Practice).xml";
# face detector.
face_detector = cv2.CascadeClassifier(path);
# run your classifier on the image
faces = face_detector.detectMultiScale(gray_im,scaleFactor=1.1,minNeighbors=7,minSize=(60,60))
print(faces);
# diaplay the bounding box on all the faces
for var in range(len(faces)):
dx = faces[var][0]
dy = faces[var][1]
w = faces[var][2]
h = faces[var][3]
cv2.rectangle(new_im, (dx,dy),(dx+w,dy+h),(255,0,0),2)
cv2_imshow(new_im) # Use cv2_imshow instead of cv2.imshow
#Importing all the pre-defined and inbuilt Libraries.
import cv2;
import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
import matplotlib.image as mimg;
from google.colab.patches import cv2_imshow
#Importing the Valuable Images path.
path='/content/office work part-2.webp';
data=cv2.imread(path);
new_im=cv2.resize(data,(512,512));
print("\n --> Total Length of the NewImage: ",new_im.shape);
#cv2.imshow("Multi faces image", im) # Replace with cv2_imshow if needed.
#Convert the color "BGR" it into the Gray Scale.
gray_im=cv2.cvtColor(new_im,cv2.COLOR_BGR2GRAY); # Change CV2 to cv2
print("\n --> Resolution of the gray image!")
print("\n",gray_im.shape)
#cv2.imshow("Multi faces image", gray_im) # Replace with cv2_imshow if needed.
path = "/content/haarcascade_frontalface_default (Practice).xml";
# face detector.
face_detector = cv2.CascadeClassifier(path);
# run your classifier on the image
faces = face_detector.detectMultiScale(gray_im,scaleFactor=1.1,minNeighbors=2,minSize=(60,60))
print(faces);
# diaplay the bounding box on all the faces
for var in range(len(faces)):
dx = faces[var][0]
dy = faces[var][1]
w = faces[var][2]
h = faces[var][3]
cv2.rectangle(new_im, (dx,dy),(dx+w,dy+h),(255,0,0),2)
cv2_imshow(new_im) # Use cv2_imshow instead of cv2.imshow
# !pip install opencv-python
# read the image
import cv2
import numpy as np
import matplotlib.pyplot as plt
path = '/content/office work.jpg';
im = cv2.imread(path)
im_new = cv2.resize(im, (512,512))
print("Resolution of the image")
print(im.shape)
#cv2.imshow("Multi faces image", im)
# covert the color (BGR) into grayscale
gray_im = cv2.cvtColor(im_new,cv2.COLOR_BGR2GRAY)
print("Resolution of the gray image")
print(gray_im.shape)
#cv2.imshow("Multi faces image", gray_im)
path = "/content/haarcascade_frontalface_default (Practice).xml";
# face detector
face_detector = cv2.CascadeClassifier(path)
# run your classifier on the image
faces = face_detector.detectMultiScale(gray_im,scaleFactor=1.1,minNeighbors=10)
print(faces)
all_faces=[]
# diaply the bounding box on all the faces
for var in range(len(faces)):
dx = faces[var][0]
dy = faces[var][1]
w = faces[var][2]
h = faces[var][3]
cv2.rectangle(im_new, (dx,dy),(dx+w,dy+h),(255,0,0),2)
# seperate out the faces
croppedFace = gray_im[dy:dy+h,dx:dx+w]
all_faces.append([croppedFace])
print(croppedFace.shape)
print(len(all_faces))
for i in range(len(all_faces)):
f = np.array(all_faces[i])[0,:,:]
newF = cv2.resize(f, (112,92))
print(newF.shape)
plt.figure(i+1)
plt.imshow(f,cmap='gray')
plt.title('Detected face')
plt.axis('off')
#cv2.imshow("face detected",im_new)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
"""#VEDIO-CAPTURE."""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import time
cam = cv2.VideoCapture(0)
path = "/content/haarcascade_frontalface_default (1).xml";
# face detector
face_detector = cv2.CascadeClassifier(path)
frame=True
while(frame==True):
val,im = cam.read()
im_new = cv2.resize(im, (512,512))
# covert the color (BGR) into grayscale
gray_im = cv2.cvtColor(im_new,cv2.COLOR_BGR2GRAY)
# run your classifier on the image
faces = face_detector.detectMultiScale(gray_im,scaleFactor=1.1,minNeighbors=10)
# disply the bounding box on all the faces
for var in range(len(faces)):
dx = faces[var][0]
dy = faces[var][1]
w = faces[var][2]
h = faces[var][3]
cv2.rectangle(im_new, (dx,dy),(dx+w,dy+h),(255,0,0),2)
cv2.imshow('camera live feed', im_new)
# desired button of your choice
if cv2.waitKey(1) & 0xFF == ord('q'):
frame=False
break
cam.release()
cv2.destroyAllWindows()
"""#As, you got notice capturing the image from the camera can't work on the Google Colab. It can works on the Plateform on:
--> Spyder Web.
--> VS Code. (Visual Studio Code).
#-------------------------------Seperate File Contains the File of Home-Work.-----------------------------
"""