Machine Learning using K-Nearest Neighbours

A Machine Learning algorithm that takes a series of questions and answers them. Written in C#, feel free to use it for any projects you have in mind.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Accord.MachineLearning;

namespace QuestionAnswerSystem
    class Program
        static void Main(string[] args)
            // Create a dataset with questions and answers
            DataTable questionsAnswers = new DataTable("QuestionsAnswers");
            questionsAnswers.Columns.Add("Questions", typeof(string));
            questionsAnswers.Columns.Add("Answers", typeof(string));

            // Add questions and answers to the dataset
            questionsAnswers.Rows.Add("What is the capital of France?", "Paris");
            questionsAnswers.Rows.Add("What is the capital of Germany?", "Berlin");
            questionsAnswers.Rows.Add("What is the capital of Spain?", "Madrid");

            // Create a K-Nearest Neighbors algorithm
            KNearestNeighbors knn = new KNearestNeighbors(k: 1);

            // Learn the questions and answers

            // Ask a question
            Console.Write("What is the capital of Italy? ");
            string question = Console.ReadLine();

            // Use the K Nearest Neighbor algorithm to answer the question
            string[] answers = knn.Decide(new string[] { question });

            // Output the result
            Console.WriteLine("Answer: " + answers[0]);

Leave a comment