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
Assistant
User
теперь всегда
Enter mode of operation (t for training, v for validation, d for dialogue): v
Validation Accuracy: 37.63%
Enter mode of operation (t for training, v for validation, d for dialogue): d
Ask a question (or type 'exit' to quit): hello
Generated Response: to
Ask a question (or type 'exit' to quit):
при каждой validation должны использоваться данные из сохраненных gob файлов при training ене должно быт всегда 37.63% процетнтов
ИИ все еще говорит только TO ИИ долженотвечать используя базу данных которую он сохранил gob
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
func getTopIndices(values []float32, n int) []int {
type kv struct {
Key int
Value float32
}
code
var ss []kv
for i, val := range values {
ss = append(ss, kv{i, val})
}
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value
})
var indices []int
for i := 0; i < n && i < len(ss); i++ {
indices = append(indices, ss[i].Key)
}
return indices
}
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.")
}
}
исправь ошибку ведь
при выборе v при validation всегда валидация на 100 процентов исправь
и при диалоге с ИИ d
Enter mode of operation (t for training, v for validation, d for dialogue): d
Ask a question (or type 'exit' to quit): hlelo
Generated Response: 115712
Ask a question (or type 'exit' to quit):
Process finished with the exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)
выдает либо 115712 либо to исправь ведь ии должен составлять ответ по базе своих робучениый должен быть внятный и понятный текст а не какаято фигня
перепиши все функции validation traiin и dialog с ИИ чтобы ен было белебирды смотри чтобы все функции и методы существовали
To address the issues you've encountered with your current code, we should start by ensuring that the training process correctly adjusts the weights so that the model can make valid predictions. We'll also adjust the dialogue function for more meaningful output and improve the validation logic. Let's refactor and enhance these functionalities:
Validation Mode Fix: Ensure predictions aren't defaulting to always correct.
Dialogue Mode Fix: Generate meaningful responses during dialogue.
Here's a refactor of the code with explanations and adjustments:
go
package main
import (
"bufio"
"encoding/csv"
"encoding/gob"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"gorgonia.org/gorgonia"
"gorgonia.org/tensor"
)
type ParsedData struct {
Input string
Output string
}
const maxTrainMessages = 100000
const maxVocabSize = 50000 // Smaller max vocab size for simplicity
func LoadCSVFiles(dirname string) ([]ParsedData, error) {
files, err := os.ReadDir(dirname)
if err != nil {
return nil, err
}
var data []ParsedData
for _, file := range files {
if strings.HasSuffix(file.Name(), ".csv") {
f, err := os.Open(filepath.Join(dirname, file.Name()))
if err != nil {
return nil, err
}
defer f.Close()
r := csv.NewReader(f)
records, err := r.ReadAll()
if err != nil {
return nil, err
}
for i := 1; i < len(records); i++ {
record := records[i]
if len(record) >= 6 {
data = append(data, ParsedData{
Input: record[4],
Output: record[5],
})
}
}
}
}
return data, nil
}
func Tokenize(text string) []string {
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Fatalf("Regex compilation failed: %v", err)
}
cleanedText := reg.ReplaceAllString(text, " ")
return strings.Fields(strings.ToLower(cleanedText))
}
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
}
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()
encoder := gob.NewEncoder(f)
return encoder.Encode(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
}
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)
}
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
}
func trainModel(trainDir string, maxTrainMessages int) {
parsedData, err := LoadCSVFiles(trainDir)
if err != nil {
log.Fatalf("Error loading CSV files: %v", err)
}
if maxTrainMessages > len(parsedData) {
maxTrainMessages = len(parsedData)
}
parsedData = parsedData[:maxTrainMessages]
fmt.Printf("Loaded %d training records\n", len(parsedData))
vocab := BuildVocab(parsedData)
if err := SaveVocabulary(vocab, "vocab.gob"); err != nil {
log.Fatalf("Error saving vocabulary: %v", err)
}
batchSize := 150
totalSamples := len(parsedData)
g := gorgonia.NewGraph()
inputSize := len(vocab)
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithInit(gorgonia.GlorotN(1.0)))
optimizer := gorgonia.NewAdamSolver(gorgonia.WithLearnRate(0.001))
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
for epoch := 0; epoch < 10; epoch++ {
for start := 0; start < totalSamples; start += batchSize {
end := start + batchSize
if end > totalSamples {
end = totalSamples
}
batchSizeActual := end - start
xVal := tensor.New(tensor.WithShape(batchSizeActual, inputSize), tensor.Of(tensor.Float32))
yVal := tensor.New(tensor.WithShape(batchSizeActual, 1), tensor.Of(tensor.Float32))
for i := start; i < end; i++ {
tokens := Tokenize(parsedData[i].Input)
inputVec := Vectorize(tokens, vocab)
offset := (i - start) * inputSize
copy(xVal.Data().([]float32)[offset:], inputVec)
outputValue := float32(0)
parsedFloat, err := strconv.ParseFloat(parsedData[i].Output, 32)
if err == nil {
outputValue = float32(parsedFloat)
}
yVal.SetAt(outputValue, i-start, 0)
}
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(batchSizeActual, inputSize), gorgonia.WithValue(xVal))
y := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(batchSizeActual, 1), gorgonia.WithValue(yVal))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
loss := gorgonia.Must(gorgonia.Mean(gorgonia.Must(gorgonia.Square(gorgonia.Must(gorgonia.Sub(yhat, y))))))
if _, err := gorgonia.Grad(loss, w); err != nil {
log.Fatalf("Failed to create computation graph: %v", err)
}
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error: %v", err)
}
optimizer.Step(gorgonia.NodesToValueGrads([]*gorgonia.Node{w}))
machine.Reset()
progress := float64(end) / float64(totalSamples) * 100
fmt.Printf("Epoch %d: Processed batch from %d to %d (%.2f%% complete)\n", epoch+1, start, end, progress)
}
}
fmt.Println("Model training complete")
if err := SaveWeights(w.Value().(*tensor.Dense), "model_weights.gob"); err != nil {
log.Fatalf("Error saving model weights: %v", err)
} else {
fmt.Println("Model weights saved successfully.")
}
}
func interactWithModel() {
weightsTensor, err := LoadWeights("model_weights.gob")
if err != nil {
log.Fatalf("Error loading model weights: %v", err)
}
vocab, err := LoadVocabulary("vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
reverseVocab := make(map[int]string)
for word, idx := range vocab {
reverseVocab[idx] = word
}
inputSize := len(vocab)
reader := bufio.NewReader(os.Stdin)
g := gorgonia.NewGraph()
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithValue(weightsTensor))
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)
xVal := tensor.New(tensor.WithShape(1, inputSize), tensor.Of(tensor.Float32))
copy(xVal.Data().([]float32), inputVec)
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(1, inputSize), gorgonia.WithValue(xVal))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
machine := gorgonia.NewTapeMachine(g)
defer machine.Close()
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error: %v", err)
}
predictionsVal := yhat.Value().Data().([]float32)
topIndices := getTopIndices(predictionsVal, 5)
var responseTokens []string
for _, idx := range topIndices {
if word, exists := reverseVocab[idx]; exists {
responseTokens = append(responseTokens, word)
}
}
response := strings.Join(responseTokens, " ")
fmt.Printf("Generated Response: %s\n", response)
machine.Reset()
}
}
func validateModel(validationDir string) {
weightsTensor, err := LoadWeights("model_weights.gob")
if err != nil {
log.Fatalf("Error loading model weights: %v", err)
}
vocab, err := LoadVocabulary("vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
validationData, err := LoadCSVFiles(validationDir)
if err != nil {
log.Fatalf("Error loading validation CSV files: %v", err)
}
g := gorgonia.NewGraph()
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(len(vocab), 1), gorgonia.WithValue(weightsTensor))
correct := 0
total := len(validationData)
for _, item := range validationData {
inputTokens := Tokenize(item.Input)
inputVec := Vectorize(inputTokens, vocab)
xVal := tensor.New(tensor.WithShape(1, len(vocab)), tensor.Of(tensor.Float32))
copy(xVal.Data().([]float32), inputVec)
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(1, len(vocab)), gorgonia.WithValue(xVal))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
machine := gorgonia.NewTapeMachine(g)
defer machine.Close()
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error: %v", err)
}
predictionsVal := yhat.Value().Data().([]float32)
predictedValue := int(predictionsVal[0] + 0.5)
// Assuming Output column has a binary classification "0" or "1"
outputResult, _ := strconv.Atoi(strings.TrimSpace(item.Output))
if predictedValue == outputResult {
correct++
}
machine.Reset()
}
accuracy := float64(correct) / float64(total) * 100
fmt.Printf("Validation Accuracy: %.2f%%\n", accuracy)
}
func getTopIndices(values []float32, n int) []int {
type kv struct {
Key int
Value float32
}
var ss []kv
for i, val := range values {
ss = append(ss, kv{i, val})
}
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value
})
var indices []int
for i := 0; i < n && i < len(ss); i++ {
indices = append(indices, ss[i].Key)
}
return indices
}
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.")
}
}
Key Changes and Fixes:
Tokenization: Ensure all text is tokenized for both input and output consistently.
Model Training: Parsing the Output as a float to handle different cases and ensuring it gets properly vectorized.
Dialogue Mode: Generates a response based on the aggregation of predictions.
Validation: Accurate validation where predictions are checked against expected output.
To make this code work more reliably with intelligible output, consider using a model more suited to language tasks, such as neural networks geared for sequence prediction. Remember this version uses vectorization and matrix multiplication, which is quite primitive for natural language understanding. For more advanced applications, explore transformer models or embeddings more attuned to NLP tasks.
From your description, it seems the model isn't learning effectively and thus isn't generating meaningful responses. There are a few potential reasons for this:
Basic Model: The current implementation uses a basic linear model. While straightforward, it's not ideal for complex natural language tasks. For better performance, consider using a neural network architecture more suited to sequence or NLP tasks, such as RNNs, LSTMs, or Transformers.
Data Preparation: Ensure that both the input and output in CSV files are prepared and preprocessed properly. Tokenization and vectorization must be consistent and meaningful.
Training Quality: The loss function or the learning rate might not be appropriately set to guarantee effective training, especially for NLP tasks. Verify that the model is training correctly and the loss is reducing over epochs.
Here’s a revised example with added flexibility to track the training process and simple debugging tips to ensure validation results match expectations:
go
package main
import (
"bufio"
"encoding/csv"
"encoding/gob"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"gorgonia.org/gorgonia"
"gorgonia.org/tensor"
)
type ParsedData struct {
Input string
Output string
}
const maxTrainMessages = 100000
const maxVocabSize = 50000
func LoadCSVFiles(dirname string) ([]ParsedData, error) {
files, err := os.ReadDir(dirname)
if err != nil {
return nil, err
}
var data []ParsedData
for _, file := range files {
if strings.HasSuffix(file.Name(), ".csv") {
f, err := os.Open(filepath.Join(dirname, file.Name()))
if err != nil {
return nil, err
}
defer f.Close()
r := csv.NewReader(f)
records, err := r.ReadAll()
if err != nil {
return nil, err
}
for i := 1; i < len(records); i++ {
record := records[i]
if len(record) >= 6 {
data = append(data, ParsedData{
Input: record[4],
Output: record[5],
})
}
}
}
}
return data, nil
}
func Tokenize(text string) []string {
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Fatalf("Regex compilation failed: %v", err)
}
cleanedText := reg.ReplaceAllString(text, " ")
return strings.Fields(strings.ToLower(cleanedText))
}
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
}
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()
encoder := gob.NewEncoder(f)
return encoder.Encode(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
}
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)
}
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
}
func trainModel(trainDir string, maxTrainMessages int) {
parsedData, err := LoadCSVFiles(trainDir)
if err != nil {
log.Fatalf("Error loading CSV files: %v", err)
}
if maxTrainMessages > len(parsedData) {
maxTrainMessages = len(parsedData)
}
parsedData = parsedData[:maxTrainMessages]
fmt.Printf("Loaded %d training records\n", len(parsedData))
vocab := BuildVocab(parsedData)
if err := SaveVocabulary(vocab, "vocab.gob"); err != nil {
log.Fatalf("Error saving vocabulary: %v", err)
}
batchSize := 150
totalSamples := len(parsedData)
g := gorgonia.NewGraph()
inputSize := len(vocab)
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithInit(gorgonia.GlorotN(1.0)))
optimizer := gorgonia.NewAdamSolver(gorgonia.WithLearnRate(0.001))
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
for epoch := 0; epoch < 10; epoch++ {
for start := 0; start < totalSamples; start += batchSize {
end := start + batchSize
if end > totalSamples {
end = totalSamples
}
batchSizeActual := end - start
xVal := tensor.New(tensor.WithShape(batchSizeActual, inputSize), tensor.Of(tensor.Float32))
yVal := tensor.New(tensor.WithShape(batchSizeActual, 1), tensor.Of(tensor.Float32))
for i := start; i < end; i++ {
tokens := Tokenize(parsedData[i].Input)
inputVec := Vectorize(tokens, vocab)
offset := (i - start) * inputSize
copy(xVal.Data().([]float32)[offset:], inputVec)
outputValue := float32(0)
if parsedData[i].Output != "" {
outputValue = float32(len(Tokenize(parsedData[i].Output)))
}
yVal.SetAt(outputValue, i-start, 0)
}
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(batchSizeActual, inputSize), gorgonia.WithValue(xVal))
y := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(batchSizeActual, 1), gorgonia.WithValue(yVal))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
loss := gorgonia.Must(gorgonia.Mean(gorgonia.Must(gorgonia.Square(gorgonia.Must(gorgonia.Sub(yhat, y))))))
if _, err := gorgonia.Grad(loss, w); err != nil {
log.Fatalf("Failed to create computation graph: %v", err)
}
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error: %v", err)
}
optimizer.Step(gorgonia.NodesToValueGrads([]*gorgonia.Node{w}))
machine.Reset()
progress := float64(end) / float64(totalSamples) * 100
fmt.Printf("Epoch %d: Processed batch from %d to %d (%.2f%% complete)\n", epoch+1, start, end, progress)
}
}
fmt.Println("Model training complete")
if err := SaveWeights(w.Value().(*tensor.Dense), "model_weights.gob"); err != nil {
log.Fatalf("Error saving model weights: %v", err)
} else {
fmt.Println("Model weights saved successfully.")
}
}
func interactWithModel() {
weightsTensor, err := LoadWeights("model_weights.gob")
if err != nil {
log.Fatalf("Error loading model weights: %v", err)
}
vocab, err := LoadVocabulary("vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
reverseVocab := make(map[int]string)
for word, idx := range vocab {
reverseVocab[idx] = word
}
inputSize := len(vocab)
reader := bufio.NewReader(os.Stdin)
g := gorgonia.NewGraph()
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithValue(weightsTensor))
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)
xVal := tensor.New(tensor.WithShape(1, inputSize), tensor.Of(tensor.Float32))
copy(xVal.Data().([]float32), inputVec)
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(1, inputSize), gorgonia.WithValue(xVal))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
machine := gorgonia.NewTapeMachine(g)
defer machine.Close()
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error: %v", err)
}
predictionsVal := yhat.Value().Data().([]float32)
// Assuming each token weight represents some meaningful prediction or response
responseTokens := selectTopWords(predictionsVal, reverseVocab, 5)
response := strings.Join(responseTokens, " ")
fmt.Printf("Generated Response: %s\n", response)
machine.Reset()
}
}
func validateModel(validationDir string) {
weightsTensor, err := LoadWeights("model_weights.gob")
if err != nil {
log.Fatalf("Error loading model weights: %v", err)
}
vocab, err := LoadVocabulary("vocab.gob")
if err != nil {
log.Fatalf("Error loading vocabulary: %v", err)
}
validationData, err := LoadCSVFiles(validationDir)
if err != nil {
log.Fatalf("Error loading validation CSV files: %v", err)
}
g := gorgonia.NewGraph()
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(len(vocab), 1), gorgonia.WithValue(weightsTensor))
correct := 0
total := len(validationData)
for _, item := range validationData {
inputTokens := Tokenize(item.Input)
inputVec := Vectorize(inputTokens, vocab)
xVal := tensor.New(tensor.WithShape(1, len(vocab)), tensor.Of(tensor.Float32))
copy(xVal.Data().([]float32), inputVec)
x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(1, len(vocab)), gorgonia.WithValue(xVal))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
machine := gorgonia.NewTapeMachine(g)
defer machine.Close()
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error: %v", err)
}
predictionsVal := yhat.Value().Data().([]float32)
predictedValue := int(predictionsVal[0] + 0.5)
outputTokens := Tokenize(item.Output)
outputValue := len(outputTokens)
if predictedValue == outputValue {
correct++
}
machine.Reset()
}
accuracy := float64(correct) / float64(total) * 100
fmt.Printf("Validation Accuracy: %.2f%%\n", accuracy)
}
func selectTopWords(predictions []float32, reverseVocab map[int]string, numWords int) []string {
type kv struct {
Key int
Value float32
}
var ss []kv
for i, val := range predictions {
ss = append(ss, kv{i, val})
}
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value
})
var responses []string
for i := 0; i < numWords && i < len(ss); i++ {
if word, ok := reverseVocab[ss[i].Key]; ok {
responses = append(responses, word)
}
}
return responses
}
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.")
}
}
Key Changes
Response Generation: Selected words for responses using selectTopWords, which interprets the model's predictions as output word probabilities (requires assumptions or data transformation to fit word prediction tasks).
Bug Fixing: Validation and accuracy now calculate against the processed expected length of the output tokens.
Further Improvements
Model Complexity: For NLP tasks, our model's architecture needs enhancement beyond mere vectorization and linear combinations. Consider RNNs, Transformers, or an embedding approach for better encoding and decoding of language context.
Data Handling: Confirm your dataset effectively conveys a meaningful relationship between inputs and responses, which might require restructuring or enriching your output labeling for enhanced learning.
Debugging: Log more detailed progress statistics for better visibility into each phase of training, validation, and interaction, which can help identify systematic errors.
Finally, training iterations and adjustments are inherently experiential. Monitor losses to ensure it's decreasing over epochs, validated further after each iteration to test model efficiency.