Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- # # Laborator 3
- # In[1]:
- import numpy as np
- import matplotlib.pyplot as plt
- # In[2]:
- #change this path
- dataPath = "C:/Users/Student/Desktop/17lab3/data/data/"
- #load train images
- train_images = np.loadtxt(dataPath + "train_images.txt")
- train_labels = np.loadtxt(dataPath + "train_labels.txt",'int8')
- print(train_images.shape)
- print(train_images.ndim)
- print(type(train_images[0,0]))
- print(train_images.size)
- print(train_images.nbytes)
- # In[3]:
- #plot the first 100 training images with their labels in a 10 x 10 subplot
- nbImages = 10
- plt.figure(figsize=(5,5))
- for i in range(nbImages**2):
- plt.subplot(nbImages,nbImages,i+1)
- plt.axis('off')
- plt.imshow(np.reshape(train_images[i,:],(28,28)),cmap = "gray")
- #plt.show()
- labels_nbImages = train_labels[:nbImages**2]
- #print(np.reshape(labels_nbImages,(nbImages,nbImages)))
- # In[4]:
- #load test images
- test_images = np.loadtxt(dataPath + "test_images.txt")
- test_labels = np.loadtxt(dataPath + "test_labels.txt",'int8')
- #plot the first 100 testing images with their labels in a 10 x 10 subplot
- nbImages = 10
- plt.figure(figsize=(5,5))
- for i in range(nbImages**2):
- plt.subplot(nbImages,nbImages,i+1)
- plt.axis('off')
- plt.imshow(np.reshape(test_images[i,:],(28,28)),cmap = "gray")
- #plt.show()
- labels_nbImages = test_labels[:nbImages**2]
- #print(np.reshape(labels_nbImages,(nbImages,nbImages)))
- # In[ ]:
- #do 1-NN, 3-NN, 5-NN, 7 -NN for the first test image
- #plot the neighbors
- v=test_images[0,:]
- distanta=np.sqrt(np.sum((v-train_images)**2,axis=1))
- indici=distanta.argsort();
- print("Predictia mea este", train_labels[indici[0]])
- #16:00
- def clasifica( elem, train, labels, k=1, dist='l1'):
- if dist == 'l2':
- distanta = np.sqrt(np.sum((elem-train)**2,axis=1))
- elif dist =='l1':
- distanta = np.sum(np.abs(elem-train),axis=1)
- else:
- print('eroare')
- #return -1
- indici = distanta.argsort()
- vecini=labels[indici[0:k]]
- contor=np.bincount(vecini)
- return contor.argmax()
- def acuratete(p,y):
- p = np.array(p)
- y = np.array(y)
- return len(p[p==y])*100/len(y)
- l,c = test_images.shape
- for k in [1,3,5,7]:
- predictii=[]
- for i in range (0,l):
- elem = test_images[i,:]
- p = clasifica(elem,train_images,train_labels,k)
- predictii.append(p)
- print(acuratete(predictii,test_labels))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement