This repository contains implementations of the Travelling Salesman Problem (TSP) algorithm and the K-Nearest Neighbors (KNN) algorithm in Python.
This script provides a solution to the Travelling Salesman Problem using a brute-force approach to find the shortest possible route that visits each city and returns to the origin city.
- Calculate the total distance for a given path.
- Find the shortest path by examining all permutations of city visits.
- Define the list of cities.
- Define the distance matrix representing distances between each pair of cities.
- Run the script to find and print the shortest path and its distance.
This script implements the K-Nearest Neighbors algorithm for classification. It predicts the class of a given test sample based on the majority class among its k
nearest neighbors in the training dataset.
- Initialize the KNN model with a specified
k
value. - Fit the model with training data.
- Predict the class labels for test data.
- Define the training data (
X_train
) and corresponding labels (y_train
). - Define the test data (
X_test
). - Initialize the KNN model and fit it with the training data.
- Predict the labels for the test data and print the predictions.
import numpy as np
from knn_algorithm import KNN
X_train = np.array([[1, 2], [2, 3], [3, 4], [4, 5]])
y_train = np.array([0, 0, 1, 1])
X_test = np.array([[2.5, 3.5]])
model = KNN(k=3)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Predictions:", predictions)