My goal is to classify samples based on their dynamic time warping distances with k-nearest-neighbor classification.
Therefore I compute a nxn
matrix, where n
is the total number of samples. This matrix contains the distance from each sample to each sample.
The precomputed
metric should be the right choice for the task since I do not want the KNeighborsClassifier
to actually compute distances between rows, it should rather just take the distances out of the matrix.
I try to split this matrix in training and test data using k-fold-validation.
However, I get unrealistic poor classification results, and I do not really understand how the precomputed
metric is supposed to be used when splitting data into training data and test data. What is wrong with the following code? Maybe the index splicing using iloc
?
X = compute_full_distance_matrix(input_data) # store distances in a pandas data frame
Y = get_target_labels() # the target labels for each row
kf = KFold(n_splits=5)
kf.get_n_splits(X)
for train_index, test_index in kf.split(X):
X_train, X_test = X.iloc[train_index, train_index], X.iloc[test_index, train_index]
Y_train, Y_test = Y[train_index], Y[test_index]
model = KNeighborsClassifier(n_neighbors=3, metric='precomputed')
model.fit(X_train, Y_train)
predictions = model.predict(X_test)
print(classification_report(Y_test,predictions))