// ParsedData представляет структуру для входных и выходных данных
type ParsedData struct {
Input string
Output string
}
// Константы для ограничения количества сообщений и размера словаря
const (
maxTrainMessages = 9900
maxVocabSize = 5000000
)
// LoadFiles загружает файлы из указанной директории
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
}
code
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++ { // Предполагается, что первая строка - заголовок
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 разбивает текст на токены
func Tokenize(text string) []string {
return strings.Fields(strings.TrimSpace(text))
}
// BuildVocab строит словарь из набора данных
func BuildVocab(data []ParsedData) map[string]int {
vocab := make(map[string]int)
wordFreq := make(map[string]int)
Assistant
code
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 преобразует токены в вектор признаков
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
}
// Сохранение и загрузка весов модели
func SaveWeights(weights *tensor.Dense, filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
// sigmoid применяет сигмоиду к каждому элементу тензора
func sigmoid(x tensor.Tensor) tensor.Tensor {
data := x.Data().([]float32)
result := make([]float32, len(data))
for i, v := range data {
result[i] = 1 / (1 + float32(math.Exp(-float64(v))))
}
return tensor.New(tensor.Of(tensor.Float32), tensor.WithBacking(result), tensor.WithShape(x.Shape()...))
}
// trainModel обучает модель на данных из trainDir
func trainModel(trainDir string, maxTrainMessages int) {
parsedData, err := LoadFiles(trainDir, maxTrainMessages)
if err != nil {
log.Fatalf("Error loading training files: %v", err)
}
code
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)
}
batchSize := 150
totalSamples := len(parsedData)
numEpochs := 10
g := gorgonia.NewGraph()
inputSize := len(vocab)
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithInit(gorgonia.GlorotN(1.0)))
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(batchSize, inputSize), gorgonia.WithName("x"))
y := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(batchSize, 1), gorgonia.WithName("y"))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
yhatSig := gorgonia.Must(gorgonia.Sigmoid(yhat)) // Apply sigmoid
// Binary cross-entropy loss
losses := gorgonia.Must(gorgonia.Sub(yhatSig, y))
squaredLoss := gorgonia.Must(gorgonia.Square(losses))
loss := gorgonia.Must(gorgonia.Mean(squaredLoss))
// Create gradients
_, err = gorgonia.Grad(loss, w)
if err != nil {
log.Fatalf("Failed to create gradients: %v", err)
}
// Initialize optimizer
optimizer := gorgonia.NewAdamSolver(gorgonia.WithLearnRate(0.001))
// Create the machine
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
for epoch := 0; epoch < numEpochs; epoch++ {
var epochLoss float64
barWidth := 50 // Width of the progress bar
// Initialize progress bar
fmt.Printf("Epoch %d/%d\n[", epoch+1, numEpochs)
for i := 0; i < barWidth; i++ {
fmt.Print(" ")
}
fmt.Print("] 0%")
fmt.Print("\r[") // Move cursor back to start of the progress bar
for start := 0; start < totalSamples; start += batchSize {
end := start + batchSize
if end > totalSamples {
end = totalSamples
}
batchSizeActual := end - start
xValData := make([]float32, batchSizeActual*inputSize)
yValData := make([]float32, batchSizeActual)
for i := start; i < end; i++ {
tokens := Tokenize(parsedData[i].Input)
inputVec := Vectorize(tokens, vocab)
copy(xValData[(i-start)*inputSize:(i-start+1)*inputSize], inputVec)
// Parse Output as float32
if parsedData[i].Output == "1" {
yValData[i-start] = 1.0
} else {
yValData[i-start] = 0.0
}
}
xVal := tensor.New(tensor.WithShape(batchSizeActual, inputSize), tensor.Of(tensor.Float32), tensor.WithBacking(xValData))
yVal := tensor.New(tensor.WithShape(batchSizeActual, 1), tensor.Of(tensor.Float32), tensor.WithBacking(yValData))
// Set node values using gorgonia.Let
if err := gorgonia.Let(x, xVal); err != nil {
log.Fatalf("Error setting x value: %v", err)
}
if err := gorgonia.Let(y, yVal); err != nil {
log.Fatalf("Error setting y value: %v", err)
}
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error during training: %v", err)
}
// Get loss value
lossData := loss.Value().Data()
lossVal, ok := lossData.(float32)
if !ok {
log.Fatalf("Unexpected type for loss value: %T", lossData)
}
epochLoss += float64(lossVal) * float64(batchSizeActual)
// Update weights
nodes := gorgonia.Nodes{w}
err = optimizer.Step(gorgonia.NodesToValueGrads(nodes))
if err != nil {
log.Fatalf("Error during optimizer step: %v", err)
}
// Update progress bar
currentBatch := start + batchSize
if currentBatch > totalSamples {
currentBatch = totalSamples
}
percent := float64(currentBatch) / float64(totalSamples)
filledLength := int(float64(barWidth) * percent) // Convert barWidth to float64 before multiplication
// Move cursor to the progress bar start
fmt.Printf("\r[") // Reset to the start of the progress bar line
for i := 0; i < filledLength; i++ {
fmt.Print("=")
}
for i := filledLength; i < barWidth; i++ {
fmt.Print(" ")
}
fmt.Printf("] %3.0f%%", percent*100)
machine.Reset()
}
averageLoss := epochLoss / float64(totalSamples)
// Move to the next line after progress bar completes
fmt.Printf("\r[")
for i := 0; i < barWidth; i++ {
fmt.Print("=")
}
fmt.Printf("] 100%% - Average Loss: %.4f\n", averageLoss)
}
fmt.Println("Model training complete")
// Save weights to models directory
if err := SaveWeights(w.Value().(*tensor.Dense), "models/model_weights.gob"); err != nil {
log.Fatalf("Error saving model weights: %v", err)
} else {
fmt.Println("Model weights saved successfully.")
}
}
// interactWithModel позволяет взаимодействовать с обученной моделью
func interactWithModel() {
weightsTensor, err := LoadWeights("models/model_weights.gob")
if err != nil {
log.Fatalf("Error loading model weights: %v", err)
}
code
vocab, err := LoadVocabulary("models/vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
inputSize := len(vocab)
reader := bufio.NewReader(os.Stdin)
// Создаем граф для предсказания
g := gorgonia.NewGraph()
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithValue(weightsTensor))
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(1, inputSize))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
yhatSig := gorgonia.Must(gorgonia.Sigmoid(yhat)) // Применяем сигмоиду
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
for {
fmt.Print("Ask a question (or type 'exit' to quit): ")
text, _ := reader.ReadString('\n')
text = strings.TrimSpace(text)
if text == "exit" {
break
}
tokens := Tokenize(text)
inputVec := Vectorize(tokens, vocab)
xValData := make([]float32, inputSize)
copy(xValData, inputVec)
xVal := tensor.New(tensor.WithShape(1, inputSize), tensor.Of(tensor.Float32), tensor.WithBacking(xValData))
// Устанавливаем значение узла x с помощью gorgonia.Let
if err := gorgonia.Let(x, xVal); err != nil {
log.Fatalf("Error setting x value: %v", err)
}
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error during interaction: %v", err)
}
predictionsVal := yhatSig.Value().Data().([]float32)
predictedProbability := predictionsVal[0]
predictedOutput := 0
if predictedProbability >= 0.5 {
predictedOutput = 1
}
var response string
if predictedOutput == 1 {
response = "Positive Response"
} else {
response = "Negative Response"
}
fmt.Printf("Generated Response: %s (Probability: %.4f)\n", response, predictedProbability)
machine.Reset()
}
}
// validateModel выполняет валидацию модели на данных из validationDir
func validateModel(validationDir string) {
weightsTensor, err := LoadWeights("models/model_weights.gob")
if err != nil {
log.Fatalf("Error loading model weights: %v", err)
}
code
vocab, err := LoadVocabulary("models/vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
validationData, err := LoadFiles(validationDir, maxTrainMessages) // Используйте подходящее ограничение
if err != nil {
log.Fatalf("Error loading validation files: %v", err)
}
fmt.Printf("Loaded %d validation records\n", len(validationData))
g := gorgonia.NewGraph()
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(len(vocab), 1), gorgonia.WithValue(weightsTensor))
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(1, len(vocab)))
y := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(1, 1))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
yhatSig := gorgonia.Must(gorgonia.Sigmoid(yhat)) // Применяем сигмоиду
// Валидация не требует градиентов, поэтому не нужно вызывать Grad
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
var totalLoss float64
correct := 0
total := len(validationData)
for idx, item := range validationData {
inputTokens := Tokenize(item.Input)
inputVec := Vectorize(inputTokens, vocab)
xValData := make([]float32, len(vocab))
copy(xValData, inputVec)
xVal := tensor.New(tensor.WithShape(1, len(vocab)), tensor.Of(tensor.Float32), tensor.WithBacking(xValData))
// Парсим Output как float32
var expectedOutput float32
if item.Output == "1" {
expectedOutput = 1.0
} else {
expectedOutput = 0.0
}
yValData := []float32{expectedOutput}
yVal := tensor.New(tensor.WithShape(1, 1), tensor.Of(tensor.Float32), tensor.WithBacking(yValData))
// Устанавливаем значения узлов x и y с помощью gorgonia.Let
if err := gorgonia.Let(x, xVal); err != nil {
log.Fatalf("Error setting x value: %v", err)
}
if err := gorgonia.Let(y, yVal); err != nil {
log.Fatalf("Error setting y value: %v", err)
}
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error during validation: %v", err)
}
predictionsVal := yhatSig.Value().Data().([]float32)
predictedProbability := predictionsVal[0]
predictedOutput := 0
if predictedProbability >= 0.5 {
predictedOutput = 1
}
// Вычисляем бинарную кросс-энтропию для текущего примера
epsilon := float32(1e-7) // Для предотвращения log(0)
p := float32(math.Min(math.Max(float64(predictedProbability), float64(epsilon)), 1-1e-7))
lossVal := -expectedOutput*float32(math.Log(float64(p))) - (1-expectedOutput)*float32(math.Log(float64(1-p)))
totalLoss += float64(lossVal)
if predictedOutput == int(expectedOutput) {
correct++
}
machine.Reset()
// Опционально: вывод прогресса
if (idx+1)%1000 == 0 || idx+1 == total {
fmt.Printf("Validated %d/%d examples\n", idx+1, total)
}
}
averageLoss := totalLoss / float64(total)
accuracy := float64(correct) / float64(total) * 100
fmt.Printf("Validation Loss: %.4f\n", averageLoss)
fmt.Printf("Validation Accuracy: %.2f%%\n", accuracy)
}
// main - точка входа программы
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()
code
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.")
}
}
сделай так чтобы ИИ делал нормальный ответ в d при диалоге с ним чтобы он составлял ответ на вопрос используя ДАННЫЕ ОБУЧЕНИЯ И САМ ПИСАЛ ВСЕ ПО БУКВЕ И СОСТАВЛЯЛ ВНЯТНОЕ НОРАЛЬНОЕ ПРЕДЛОЖЕНИЕ
например я пишу ему hi а он должен дать развернутый ответ типо hello i am AI по базе обучения сам ссотавить ответ
скрипт не должекн быть маленьким напиши его цилеком и полностью
To create an AI that can generate coherent and meaningful responses based on user input, we need to shift from a simple binary classification model to a more sophisticated approach. The current model you've implemented uses logistic regression to classify inputs into binary outputs (e.g., "Positive" or "Negative"). To achieve dynamic and contextually relevant responses, we need to implement a sequence-to-sequence (Seq2Seq) model or a retrieval-based system that leverages similarity measures to select appropriate responses from the training data.
Given the complexity of implementing a full-fledged generative model in Go using Gorgonia, I'll provide a retrieval-based approach where the AI selects the most relevant response from the training data based on the similarity of the user input. This method is simpler to implement and can still provide meaningful interactions.
Below is the complete Go script with the necessary modifications:
go
package main
import (
"bufio"
"encoding/csv"
"encoding/gob"
"fmt"
"io/ioutil"
"log"
"math"
"math/rand"
"os"
"path/filepath"
"sort"
"strings"
"time"
"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 builds 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]
}
// Reserve index 0 for padding and 1 for unknown tokens
vocab["<PAD>"] = 0
vocab["<UNK>"] = 1
for i, kv := range freqs {
vocab[kv.Key] = i + 2
}
return vocab
}
// Vectorize converts tokens into a feature vector
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
} else {
vector[vocab["<UNK>"]] += 1
}
}
return vector
}
// SaveWeights saves model weights to a file
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 model weights from a file
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 to a file
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 from a file
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 calculates the cosine similarity between two vectors
func cosineSimilarity(a, b []float32) float64 {
if len(a) != len(b) {
return 0
}
var dot, normA, normB float64
for i := 0; i < len(a); 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))
}
// Shuffle shuffles a slice of ParsedData
func Shuffle(data []ParsedData) {
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(data), func(i, j int) {
data[i], data[j] = data[j], data[i]
})
}
// trainModel trains the model by preparing data vectors
func trainModel(trainDir string, maxTrainMessages int) ([]ParsedData, map[string]int, error) {
parsedData, err := LoadFiles(trainDir, maxTrainMessages)
if err != nil {
return nil, nil, fmt.Errorf("error loading training files: %v", err)
}
fmt.Printf("Loaded %d training records\n", len(parsedData))
vocab := BuildVocab(parsedData)
// Shuffle the data to ensure randomness
Shuffle(parsedData)
// Create models directory if it doesn't exist
if err := os.MkdirAll("models", os.ModePerm); err != nil {
return nil, nil, fmt.Errorf("error creating models directory: %v", err)
}
// Save vocabulary to models directory
if err := SaveVocabulary(vocab, "models/vocab.gob"); err != nil {
return nil, nil, fmt.Errorf("error saving vocabulary: %v", err)
}
// Optionally, preprocess and save input-output vectors for faster retrieval
// Here, we skip this step for simplicity
fmt.Println("Training data is ready.")
return parsedData, vocab, nil
}
// interactWithModel allows interaction with the trained model
func interactWithModel(parsedData []ParsedData, vocab map[string]int) {
reader := bufio.NewReader(os.Stdin)
fmt.Println("You can start chatting with the AI. Type 'exit' to quit.")
for {
fmt.Print("You: ")
text, err := reader.ReadString('\n')
if err != nil {
log.Fatalf("Error reading input: %v", err)
}
text = strings.TrimSpace(text)
if strings.ToLower(text) == "exit" {
fmt.Println("Goodbye!")
break
}
tokens := Tokenize(text)
inputVec := Vectorize(tokens, vocab)
// Find the most similar input in the training data
var bestMatch *ParsedData
highestSim := -1.0
for _, data := range parsedData {
responseTokens := Tokenize(data.Input)
responseVec := Vectorize(responseTokens, vocab)
sim := cosineSimilarity(inputVec, responseVec)
if sim > highestSim {
highestSim = sim
bestMatch = &data
}
}
// If a good match is found, respond with the corresponding output
if bestMatch != nil && highestSim > 0.1 { // Threshold can be adjusted
fmt.Printf("AI: %s\n", bestMatch.Output)
} else {
// Default response if no good match is found
defaultResponses := []string{
"I'm not sure I understand. Could you please elaborate?",
"Can you tell me more about that?",
"Interesting! Let's discuss further.",
"Could you clarify that for me?",
"That's fascinating. What else can you share?",
}
fmt.Printf("AI: %s\n", defaultResponses[rand.Intn(len(defaultResponses))])
}
}
}
// validateModel performs model validation on data from validationDir
func validateModel(validationDir string, vocab map[string]int) {
// For retrieval-based approach, validation can measure how often the most similar match has the correct or expected response
// Here, we implement a simple validation by checking if the top match's output is as expected
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 correct int
var total float64
for _, item := range validationData {
inputTokens := Tokenize(item.Input)
inputVec := Vectorize(inputTokens, vocab)
// Find the most similar input in the training data
var bestMatch *ParsedData
highestSim := -1.0
for _, data := range validationData {
responseTokens := Tokenize(data.Input)
responseVec := Vectorize(responseTokens, vocab)
sim := cosineSimilarity(inputVec, responseVec)
if sim > highestSim {
highestSim = sim
bestMatch = &data
}
}
if bestMatch != nil && highestSim > 0.1 { // Threshold can be adjusted
if strings.ToLower(bestMatch.Output) == strings.ToLower(item.Output) {
correct++
}
}
total++
}
accuracy := (float64(correct) / total) * 100
fmt.Printf("Validation Accuracy: %.2f%%\n", accuracy)
}
// main is the 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":
parsedData, vocab, err := trainModel("train", maxTrainMessages)
if err != nil {
log.Fatalf("Training failed: %v", err)
}
// Optionally, save the prepared data for faster access during interaction
// Here, we skip saving for simplicity
fmt.Println("Training completed successfully.")
case "v":
vocab, err := LoadVocabulary("models/vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
validateModel("valid", vocab)
case "d":
vocab, err := LoadVocabulary("models/vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
parsedData, err := LoadFiles("train", maxTrainMessages)
if err != nil {
log.Fatalf("Error loading training data for interaction: %v", err)
}
interactWithModel(parsedData, vocab)
default:
fmt.Println("Unknown mode. Use 't' for training, 'v' for validation, or 'd' for dialogue.")
}
}
Explanation of Changes
Retrieval-Based Approach:
Similarity Measurement: Instead of using a binary classifier, the AI now selects the most similar input from the training data and responds with the corresponding output. This is done using cosine similarity between the input vectors.
Default Responses: If no sufficiently similar input is found (based on a threshold), the AI responds with a default message, making the interaction feel more natural.
Vocabulary Handling:
Special Tokens: Added <PAD> and <UNK> tokens to handle padding and unknown words.
Unknown Words: Words not present in the vocabulary are mapped to <UNK> to handle out-of-vocabulary scenarios gracefully.
Data Shuffling:
Shuffled the training data to ensure randomness, which can help in better similarity matching.
Enhanced Interaction (interactWithModel):
Similarity-Based Response: The AI now finds the most similar input in the training data and uses its corresponding output as the response.
Dynamic Responses: If a close match isn't found, the AI provides a default response to maintain the conversation flow.
Validation (validateModel):
Accuracy Calculation: The validation now checks how often the AI's top match has the correct or expected response, providing an accuracy metric.
User-Friendly Enhancements:
Default Conversations: Added multiple default responses to make the AI's replies feel more varied and less robotic.
Exit Mechanism: Users can type 'exit' to end the conversation gracefully.
How to Use the Updated Script
Prepare Your Data:
Training Data (train Directory): Ensure that your training data is placed in the train directory. It can be in CSV or TXT format.
CSV Format: The first column should be the user input, and the second column should be the AI's response.
TXT Format: Each line should follow the format input:output.
Validation Data (valid Directory): Similarly, place your validation data in the valid directory following the same format.
Training the Model:
bash
go run your_script.go
When prompted, enter t to start the training. This will build the vocabulary and prepare the data.
Validating the Model:
bash
go run your_script.go
Enter v when prompted to perform validation and see the accuracy of the AI.
Interacting with the AI:
bash
go run your_script.go
Enter d to start a dialogue with the AI. Type your messages, and the AI will respond based on the most similar input from the training data.
Notes and Recommendations
Data Quality: The effectiveness of the AI heavily relies on the quality and breadth of your training data. Ensure that the train directory contains diverse and comprehensive input-output pairs to cover various conversational scenarios.
Threshold Tuning: The similarity threshold (0.1 in the script) determines how sensitive the AI is in selecting responses. You might need to adjust this value based on your dataset and desired responsiveness.
Extensibility: While this retrieval-based approach is effective for many use cases, for more dynamic and contextually rich conversations, consider implementing a Seq2Seq model or integrating with more advanced NLP frameworks.
Performance Optimization: For large datasets, computing cosine similarity on-the-fly can be computationally expensive. Consider precomputing embeddings or using more efficient search algorithms (like Approximate Nearest Neighbors) for scalability.
Error Handling: The script includes basic error handling, but you might want to expand it further to handle edge cases and unexpected inputs gracefully.
Extending Vocabulary: Over time, as users interact with the AI, you might encounter words that are not in the initial vocabulary. Implementing mechanisms to update the vocabulary dynamically can enhance the AI's versatility.
This updated script provides a more interactive and engaging AI experience by leveraging similarity measures to select appropriate responses. While it doesn't generate sentences from scratch, it ensures that responses are contextually relevant based on the provided training data.