Finding Related Words using Natural Language Processing in SwiftUI

DevTechie Inc
Jul 14, 2023

Finding Related Words using Natural Language Processing in SwiftUI

Another cool feature that Natural Language framework provides out of the box is the ability to find related or similar words.

NLEmbedding class was introduced in iOS 13 and it creates a map of string to vectors which are used to locate neighboring strings. It uses vector based proximity to find similar strings.

The vocabulary is the entire set of strings in an embedding. Each string in the vocabulary has a vector, which is an array of doubles, and each double corresponds to a dimension in the embedding. An NLEmbedding uses these vectors to determine the distance between two strings, or to find the nearest neighbors of a string in the vocabulary. The higher the similarity of any two strings, the smaller the distance is between them.

The API is very simple, we just create a request to find word embedding for given language and ask the system to generate neighboring strings.

Let’s start with a basic view.

import NaturalLanguage
struct DevTechieNLEmbeddingExample: View {
    @State private var inputString = ""
    
    @State private var results = [String]()
    
    var body: some View {
        NavigationStack {
            VStack {
                List(results, id: \.self) {item in
                    Text(item)
                }
                HStack {
                    TextField("Type a word", text: $inputString)
                        .textFieldStyle(.roundedBorder)
                    Button {
                        
                    } label: {
                        Image(systemName: "paperplane.fill")
                    }
}
            }
            .padding()
            .navigationTitle("DevTechie")
        }
    }
}

We will use TextField to type string and button will help us process and find the similar words.

Let’s create NLEmbedding instance for english language

let embedding = NLEmbedding.wordEmbedding(for: .english)!

We will use NLEmbedding’s neighbors function to get five similar words. This method returns word and its distance from the input string.

We will lowercase the input so distance vector can be computed.

let neighbors = embedding.neighbors(for: inputString.lowercased(), maximumCount: 5)

Complete example will look like this

import NaturalLanguage
struct DevTechieNLEmbeddingExample: View {
    @State private var inputString = ""
    
    @State private var results = [String]()
    
    let embedding = NLEmbedding.wordEmbedding(for: .english)!
    
    var body: some View {
        NavigationStack {
            VStack {
                List(results, id: \.self) {item in
                    Text(item)
                }
                HStack {
                    TextField("Type a word", text: $inputString)
                        .textFieldStyle(.roundedBorder)
Button {
                        results = []
                        let neighbors = embedding.neighbors(for: inputString.lowercased(), maximumCount: 5)
                        for neighbor in neighbors {
                            results.append("Word: \(neighbor.0), Distance: \(neighbor.1.formatted())")
                        }
                    } label: {
                        Image(systemName: "paperplane.fill")
                    }
}
            }
            .padding()
            .navigationTitle("DevTechie")
        }
    }
}