To create an AI that can generate meaningful and coherent responses based on your training data, you need to shift from a simple binary classification model to a retrieval-based system. This system will find the most similar input from your training data and respond with the corresponding output. This approach is more straightforward and effective for generating responses without implementing complex generative models.
Below is the complete Go script implementing a retrieval-based dialogue system. This system loads training data, builds a vocabulary, vectorizes inputs, and during interaction, it finds the most similar input from the training data and returns its corresponding response.
package main
import (
"bufio"
"encoding/csv"
"encoding/gob"
"fmt"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"sort"
"strings"
"gorgonia.org/gorgonia"
"gorgonia.org/tensor"
)
// ParsedData represents the structure for input and output data
type ParsedData struct {
Input string
Output string
}
// Constants to limit the number of messages and vocabulary size
const (
maxTrainMessages = 9900
maxVocabSize = 5000000
)
// LoadFiles loads files from the specified directory
func LoadFiles(dirname string, maxMessages int) ([]ParsedData, error) {
var data []ParsedData
err := filepath.WalkDir(dirname, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || len(data) >= maxMessages {
return nil
}
if strings.HasSuffix(d.Name(), ".csv") {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
r := csv.NewReader(f)
records, err := r.ReadAll()
if err != nil {
return err
}
for i := 1; i < len(records) && len(data) < maxMessages; i++ { // Assume first line is header
record := records[i]
if len(record) >= 2 {
data = append(data, ParsedData{
Input: record[0],
Output: record[1],
})
}
}
} else if strings.HasSuffix(d.Name(), ".txt") {
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if len(data) >= maxMessages {
break
}
parts := strings.Split(line, ":")
if len(parts) > 1 {
data = append(data, ParsedData{
Input: strings.TrimSpace(parts[0]),
Output: strings.TrimSpace(parts[1]),
})
}
}
}
return nil
})
return data, err
}
// Tokenize splits text into tokens
func Tokenize(text string) []string {
return strings.Fields(strings.TrimSpace(text))
}
// BuildVocab constructs a vocabulary from the dataset
func BuildVocab(data []ParsedData) map[string]int {
vocab := make(map[string]int)
wordFreq := make(map[string]int)
for _, item := range data {
tokens := append(Tokenize(item.Input), Tokenize(item.Output)...)
for _, token := range tokens {
wordFreq[token]++
}
}
type kv struct {
Key string
Value int
}
var freqs []kv
for k, v := range wordFreq {
freqs = append(freqs, kv{k, v})
}
sort.Slice(freqs, func(i, j int) bool {
return freqs[i].Value > freqs[j].Value
})
if len(freqs) > maxVocabSize {
freqs = freqs[:maxVocabSize]
}
for i, kv := range freqs {
vocab[kv.Key] = i
}
return vocab
}
// Vectorize converts tokens into feature vectors
func Vectorize(tokens []string, vocab map[string]int) []float32 {
vector := make([]float32, len(vocab))
for _, token := range tokens {
if idx, exists := vocab[token]; exists {
vector[idx] += 1
}
}
return vector
}
// SaveWeights saves the model weights
func SaveWeights(weights *tensor.Dense, filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
encoder := gob.NewEncoder(f)
return encoder.Encode(weights)
}
// LoadWeights loads the model weights
func LoadWeights(filename string) (*tensor.Dense, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
var weights tensor.Dense
decoder := gob.NewDecoder(f)
if err := decoder.Decode(&weights); err != nil {
return nil, err
}
return &weights, nil
}
// SaveVocabulary saves the vocabulary
func SaveVocabulary(vocab map[string]int, filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
encoder := gob.NewEncoder(f)
return encoder.Encode(vocab)
}
// LoadVocabulary loads the vocabulary
func LoadVocabulary(filename string) (map[string]int, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
var vocab map[string]int
decoder := gob.NewDecoder(f)
if err := decoder.Decode(&vocab); err != nil {
return nil, err
}
return vocab, nil
}
// cosineSimilarity computes cosine similarity between two vectors
func cosineSimilarity(a, b []float32) float64 {
var dot, normA, normB float64
for i := 0; i < len(a) && i < len(b); i++ {
dot += float64(a[i] * b[i])
normA += float64(a[i] * a[i])
normB += float64(b[i] * b[i])
}
if normA == 0 || normB == 0 {
return 0
}
return dot / (math.Sqrt(normA) * math.Sqrt(normB))
}
// trainModel processes and saves the model components (vocab and input vectors)
func trainModel(trainDir string, maxTrainMessages int) {
parsedData, err := LoadFiles(trainDir, maxTrainMessages)
if err != nil {
log.Fatalf("Error loading training files: %v", err)
}
fmt.Printf("Loaded %d training records\n", len(parsedData))
vocab := BuildVocab(parsedData)
// Create models directory if it doesn't exist
if err := os.MkdirAll("models", os.ModePerm); err != nil {
log.Fatalf("Error creating models directory: %v", err)
}
// Save vocabulary to models directory
if err := SaveVocabulary(vocab, "models/vocab.gob"); err != nil {
log.Fatalf("Error saving vocabulary: %v", err)
}
// Vectorize all training inputs and save them
inputVectors := make([][]float32, len(parsedData))
for i, item := range parsedData {
tokens := Tokenize(item.Input)
inputVectors[i] = Vectorize(tokens, vocab)
}
// Save input vectors
inputVectorsFile, err := os.Create("models/input_vectors.gob")
if err != nil {
log.Fatalf("Error creating input vectors file: %v", err)
}
defer inputVectorsFile.Close()
encoder := gob.NewEncoder(inputVectorsFile)
if err := encoder.Encode(inputVectors); err != nil {
log.Fatalf("Error encoding input vectors: %v", err)
}
// Save outputs
outputs := make([]string, len(parsedData))
for i, item := range parsedData {
outputs[i] = item.Output
}
outputsFile, err := os.Create("models/outputs.gob")
if err != nil {
log.Fatalf("Error creating outputs file: %v", err)
}
defer outputsFile.Close()
if err := encoder.Encode(outputs); err != nil {
log.Fatalf("Error encoding outputs: %v", err)
}
fmt.Println("Training data processed and saved successfully.")
}
// interactWithModel allows interaction with the trained model
func interactWithModel() {
vocab, err := LoadVocabulary("models/vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
// Load input vectors
inputVectorsFile, err := os.Open("models/input_vectors.gob")
if err != nil {
log.Fatalf("Error loading input vectors: %v", err)
}
defer inputVectorsFile.Close()
var inputVectors [][]float32
decoder := gob.NewDecoder(inputVectorsFile)
if err := decoder.Decode(&inputVectors); err != nil {
log.Fatalf("Error decoding input vectors: %v", err)
}
// Load outputs
outputsFile, err := os.Open("models/outputs.gob")
if err != nil {
log.Fatalf("Error loading outputs: %v", err)
}
defer outputsFile.Close()
var outputs []string
decoder = gob.NewDecoder(outputsFile)
if err := decoder.Decode(&outputs); err != nil {
log.Fatalf("Error decoding outputs: %v", err)
}
reader := bufio.NewReader(os.Stdin)
fmt.Println("AI is ready to chat! Type 'exit' to quit.")
for {
fmt.Print("You: ")
text, _ := reader.ReadString('\n')
text = strings.TrimSpace(text)
if strings.ToLower(text) == "exit" {
fmt.Println("AI: Goodbye!")
break
}
tokens := Tokenize(text)
inputVec := Vectorize(tokens, vocab)
var bestMatchIdx int
var bestSimilarity float64 = -1
for i, trainVec := range inputVectors {
sim := cosineSimilarity(inputVec, trainVec)
if sim > bestSimilarity {
bestSimilarity = sim
bestMatchIdx = i
}
}
if bestSimilarity > 0.1 { // Threshold to decide if a response is found
response := outputs[bestMatchIdx]
fmt.Printf("AI: %s\n", response)
} else {
fmt.Println("AI: I'm not sure how to respond to that.")
}
}
}
// validateModel performs validation on the model using validation data
func validateModel(validationDir string) {
vocab, err := LoadVocabulary("models/vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
// Load input vectors
inputVectorsFile, err := os.Open("models/input_vectors.gob")
if err != nil {
log.Fatalf("Error loading input vectors: %v", err)
}
defer inputVectorsFile.Close()
var inputVectors [][]float32
decoder := gob.NewDecoder(inputVectorsFile)
if err := decoder.Decode(&inputVectors); err != nil {
log.Fatalf("Error decoding input vectors: %v", err)
}
// Load outputs
outputsFile, err := os.Open("models/outputs.gob")
if err != nil {
log.Fatalf("Error loading outputs: %v", err)
}
defer outputsFile.Close()
var outputs []string
decoder = gob.NewDecoder(outputsFile)
if err := decoder.Decode(&outputs); err != nil {
log.Fatalf("Error decoding outputs: %v", err)
}
validationData, err := LoadFiles(validationDir, maxTrainMessages) // Use appropriate limit
if err != nil {
log.Fatalf("Error loading validation files: %v", err)
}
fmt.Printf("Loaded %d validation records\n", len(validationData))
var totalSimilarity float64
var matches int
for _, item := range validationData {
tokens := Tokenize(item.Input)
inputVec := Vectorize(tokens, vocab)
var bestMatchIdx int
var bestSimilarity float64 = -1
for i, trainVec := range inputVectors {
sim := cosineSimilarity(inputVec, trainVec)
if sim > bestSimilarity {
bestSimilarity = sim
bestMatchIdx = i
}
}
totalSimilarity += bestSimilarity
// Optionally, check if the response is correct based on some criteria
// Here, we'll just count all as matches above a threshold
if bestSimilarity > 0.1 {
matches++
}
}
averageSimilarity := totalSimilarity / float64(len(validationData))
accuracy := float64(matches) / float64(len(validationData)) * 100
fmt.Printf("Validation Average Similarity: %.4f\n", averageSimilarity)
fmt.Printf("Validation Accuracy: %.2f%%\n", accuracy)
}
// main - entry point of the program
func main() {
fmt.Print("Enter mode of operation (t for training, v for validation, d for dialogue): ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
mode := scanner.Text()
switch mode {
case "t":
trainModel("train", maxTrainMessages)
case "v":
validateModel("valid")
case "d":
interactWithModel()
default:
fmt.Println("Unknown mode. Use 't' for training, 'v' for validation, or 'd' for dialogue.")
}
}
Explanation of Changes
-
Retrieval-Based Approach:
- Instead of training a neural network to classify inputs into binary categories, the script now uses a retrieval-based approach.
- The system finds the most similar input from the training data and returns its corresponding output.
-
Training Phase (trainModel Function):
- Loads and processes the training data.
- Builds the vocabulary from the training data.
- Vectorizes all training inputs and saves these vectors along with their corresponding outputs.
-
Interaction Phase (interactWithModel Function):
- Loads the pre-processed input vectors and outputs.
- When the user inputs a message, it vectorizes the input and computes the cosine similarity with all training input vectors.
- Selects the training input with the highest similarity and returns the corresponding output as the AI's response.
- A similarity threshold is used to determine if the AI can confidently respond or not.
-
Validation Phase (validateModel Function):
- Similar to the interaction phase but against a separate validation dataset to assess the model's performance.
-
Utility Functions:
cosineSimilarity calculates the similarity between two vectors.
- Functions for saving and loading vocabularies, input vectors, and outputs using
gob for serialization.
How to Use the Script
-
Prepare Training Data:
- Create a directory named
train containing your training data.
- The training data can be in
.csv or .txt formats.
- For
.csv: The first column should be the input (e.g., user questions), and the second column should be the output (e.g., AI responses).
- For
.txt: Each line should contain an input and output separated by a colon (:), e.g., Hi:Hello, I am AI.
-
Train the Model:
- Run the script and enter
t when prompted to start the training process.
- This will process the training data and save the necessary components in the
models directory.
go run your_script.go
# Enter mode of operation (t for training, v for validation, d for dialogue): t
-
Interact with the AI:
- After training, run the script again and enter
d to start a dialogue with the AI.
go run your_script.go
# Enter mode of operation (t for training, v for validation, d for dialogue): d
- Type your messages, and the AI will respond based on the training data.
- Type
exit to end the conversation.
You: Hi
AI: Hello, I am AI.
You: How are you?
AI: I'm fine, thank you!
You: exit
AI: Goodbye!
-
Validate the Model:
- You can also validate the model using a separate validation dataset placed in a directory named
valid.
go run your_script.go
# Enter mode of operation (t for training, v for validation, d for dialogue): v
Notes
-
Vectorization:
- The current approach uses bag-of-words for vectorization, which counts the frequency of each word in the input. This is simple but effective for similarity-based retrieval.
-
Similarity Threshold:
- The threshold (
0.1 in this case) determines whether the AI should respond or indicate uncertainty. You might need to adjust this based on your dataset.
-
Scalability:
- For larger datasets, computing cosine similarity with every training input can be slow. Consider using more efficient nearest neighbor search algorithms or indexing methods for scalability.
-
Enhancements:
- Implement more advanced vectorization techniques like TF-IDF or word embeddings for better similarity measurements.
- Incorporate context handling to make the AI maintain conversations over multiple turns.
- Extend the AI to handle more complex dialogue patterns and responses.
This retrieval-based approach provides a simple yet effective way to generate coherent and contextually relevant responses based on your training data. As you grow your dataset and refine your methods, you can enhance the AI's capabilities further.