Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

K-Nearest Neighbor Implementation for Strings (Unstructured data) in Java

I'm looking for implementation for K-Nearest Neighbor algorithm in Java for unstructured data. I found many implementation for numeric data, however how I can implement it and calculate the Euclidean Distance for text (Strings).

Here is one example for double:

public static double EuclideanDistance(double [] X, double []Y)
{
    int count = 0;
    double distance = 0.0;
    double sum = 0.0;
    if(X.length != Y.length)
    {
        try {
            throw new Exception("the number of elements" + 
                      " in X must match the number of elements in Y");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    else
    {
        count = X.length;
    }
    for (int i = 0; i < count; i++)
    {
        sum = sum + Math.pow(Math.abs(X[i] - Y[i]),2);
    }
    distance = Math.sqrt(sum);
    return distance;
}

How I can implement it for Strings (unstructured data)? For example, Class 1: "It was amazing. I loved it" "It is perfect movie"

Class 2: "Boring. Boring. Boring." "I do not like it"

How can we implement KNN on such type of data and calculate Euclidean Distance?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You correctly noticed that the only thing you have to do is to define the notion of distance between your strings. The problem is that it is task dependent. It can be anything from let's assign the distance to 1 if both strings have a world 'data' in it and 0 otherwise to something more complex like Okapi BM25.

Take a look at various string metrics or may be python implementation of tf-idf.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...