Given a dataset of images, implement a function to perform a query image similarity search. The function should take in a query image and return the most similar image from the dataset.
Input: Query image vector q, dataset of image vectors D
q = [0.1, 0.2, 0.3, ...]D = [[0.4, 0.5, 0.6, ...], [0.7, 0.8, 0.9, ...], ...]D to q.Input: Query image vector q, dataset of image vectors D
q = [0.1, 0.2, 0.3, ...]D = [[0.1, 0.2, 0.3, ...], [0.4, 0.5, 0.6, ...], ...]D to q.`python import numpy as np
def euclidean_distance(a, b): return np.sqrt(np.sum((a - b) ** 2))
def query_image_similarity_search(query_image, dataset): min_distance = float('inf') most_similar_index = -1
for i, image in enumerate(dataset):
distance = euclidean_distance(query_image, image)
if distance < min_distance:
min_distance = distance
most_similar_index = i
return most_similar_index
query_image = np.array([0.1, 0.2, 0.3]) dataset = [np.array([0.4, 0.5, 0.6]), np.array([0.7, 0.8, 0.9])] print(query_image_similarity_search(query_image, dataset)) `
This solution calculates the Euclidean distance between the query image and each image in the dataset, then returns the index of the image with the smallest distance.
The complete problem statement, examples, constraints, hints, and solution for the "ML Coding - Query Image Similarity Search" question asked at Apple have been provided above.