import numpy as np
from collections import Counter
class KNN:
def __init__(self, k=3):
self.k = k
def fit(self, X, y):
self.X_train = X
self.y_train = y
def predict(self, X):
predictions = []
for i in range(len(X)):
distances = []
for j in range(len(self.X_train)):
distance = np.sqrt(np.sum((X[i] - self.X_train[j])**2))
distances.append([distance, j])
distances = sorted(distances)
neighbors = [self.y_train[distance[1]] for distance in distances[:self.k]]
prediction = Counter(neighbors).most_common(1)
predictions.append(prediction[0][0])
return predictions
Here, the KNN class implements the KNN algorithm with an optional parameter k to specify the number of nearest neighbors to consider. The fit method takes in the training data (X) and corresponding labels (y) to store it as class attributes. The predict method takes in the test data (X) and returns predictions for each test instance.
In the predict method, for each test instance, the distances between the test instance and all training instances are calculated using the Euclidean Distance formula. The distances are sorted in ascending order and the k nearest neighbors are selected. The most common label among the nearest neighbors is returned as the predicted label for the test instance.
where hrs_selection1, hrs_selection2, ..., hrs_selectionN are the corresponding HRS selections for image1.jpeg, image2.jpeg, ..., imageN.jpeg, respectively.
import tensorflow as tf
import os
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
# Define function to load and preprocess image
def load_and_preprocess_image(filename):
img_raw = tf.io.read_file(filename)
img = tf.image.decode_jpeg(img_raw, channels=3)
img = tf.image.resize(img, (299, 299))
img = tf.keras.applications.inception_v3.preprocess_input(img)
return img
# Define function to extract embedding vector from Inception-V3 or ResNet50 model
def extract_embedding_vector(model, image_path):
img = load_and_preprocess_image(image_path)
img = tf.expand_dims(img, axis=0)
embedding_vector = model.predict(img)
embedding_vector = np.squeeze(embedding_vector)
return embedding_vector
# Define function to create dictionary of embedding vectors and corresponding HRS selection
def create_embedding_dict(model, image_dir, hrs_selection_path):
embedding_dict = {}
with open(hrs_selection_path, 'r') as f:
lines = f.readlines()
for line in lines:
img_path, hrs_selection = line.split()
img_path = os.path.join(image_dir, img_path)
embedding_vector = extract_embedding_vector(model, img_path)
embedding_dict[tuple(embedding_vector)] = hrs_selection
return embedding_dict
# Define function to extract first 2 classes from ImageNet validation set
def extract_classes(image_dir, class1, class2):
class1_dir = os.path.join(image_dir, class1)
class2_dir = os.path.join(image_dir, class2)
class1_images = [os.path.join(class1_dir, filename) for filename in os.listdir(class1_dir)]
class2_images = [os.path.join(class2_dir, filename) for filename in os.listdir(class2_dir)]
images = class1_images + class2_images
return images
# Define function to divide data into training and testing sets
def split_data(embedding_dict, train_size):
embedding_vectors = list(embedding_dict.keys())
hrs_selections = list(embedding_dict.values())
num_train = int(train_size * len(embedding_vectors))
X_train = embedding_vectors[:num_train]
y_train = hrs_selections[:num_train]
X_test = embedding_vectors[num_train:]
y_test = hrs_selections[num_train:]
return X_train, y_train, X_test, y_test
# Define function to apply KNN algorithm
def apply_knn(X_train, y_train, X_test, k):
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
predicted_qs = knn.predict(X_test)
return predicted_qs
# Define paths to validation image folder, HRS selection file, and pre-trained model weights
validation_image_dir = '/path/to/ImageNet/validation/'
hrs_selection_path = '/path/to/hrs_selection.txt'
model_weights_path = 'inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5' # for Inception-V3 model
# model_weights_path = 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' # for ResNet50 model
# Load pre-trained Inception-V3 or ResNet50 model without the top (fully connected) layer
model = tf.keras.applications.InceptionV3(include_top=False, weights=model_weights_path, pooling='avg') # for Inception-V3 model
# model = tf.keras.applications.ResNet50(include_top=False, weights=model_weights_path, pooling='avg') # for ResNet50 model
# Extract first 2 classes from ImageNet validation set
class1 = 'class1'
class2 = 'class2'
images = extract_classes(validation_image_dir, class1, class2)
# Create dictionary of embedding vectors and corresponding HRS selection for the first 2000 images
embedding_dict = create_embedding_dict(model, validation_image_dir, hrs_selection_path)
# Divide data into training and testing sets
X_train, y_train, X_test, y_test = split_data(embedding_dict, train_size=0.8)
# Apply KNN algorithm
k = 5
predicted_qs = apply_knn(X_train, y_train, X_test, k)
# Calculate accuracy of predicted QFs
top1_correct = 0
top5_correct = 0
for i in range(len(predicted_qs)):
if predicted_qs[i] == y_test[i]:
top5_correct += 1
if i < 1:
top1_correct += 1
top1_accuracy = top1_correct / len(predicted_qs)
top5_accuracy = top5_correct / len(predicted_qs)
print('Top-1 Accuracy: %.3f' % top1_accuracy)
print('Top-5 Accuracy: %.3f' % top5_accuracy)
where hrs_selection1, hrs_selection2, ..., hrs_selectionN are the corresponding HRS selections for image1.jpeg, image2.jpeg, ..., imageN.jpeg, respectively. Also, the code assumes that the HRS selections are categorical variables. If the HRS selections are numerical variables, then you may need to use regression instead of classification in the KNN algorithm.