// ParsedData представляет структуру для входных и выходных данных
type ParsedData struct {
Input string
Output string
}
// Константы для ограничения количества сообщений и размера словаря
const (
maxTrainMessages = 10990
maxVocabSize = 500000
numEpochs = 150
batchSize = 15
)
// 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
}
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)
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()
Assistant
The error message Node's expected shape is (100, 14342). Got (90, 14342) instead indicates that there is a mismatch between the expected shape of the tensor and the shape provided during the training process. This mismatch occurs because you've set up a graph expecting a fixed batch size of 100, but the actual data for the last batch contains only 90 samples (as it's the remainder of the total samples).
User
напши train целиком и полностью
Assistant
User
Enter mode of operation (t for training, v for validation, d for dialogue): t
Loaded 10990 training records
2024/11/07 19:54:36 Error setting x value: Node's expected shape is (-1, 14342). Got (15, 14342) instead
// trainModel обучает модель на данных из trainDir
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)
// Создаем директорию models, если она не существует
if err := os.MkdirAll("models", os.ModePerm); err != nil {
log.Fatalf("Error creating models directory: %v", err)
}
// Сохраняем словарь в директорию models
if err := SaveVocabulary(vocab, "models/vocab.gob"); err != nil {
log.Fatalf("Error saving vocabulary: %v", err)
}
batchSize := 100
totalSamples := len(parsedData)
numEpochs := 5
g := gorgonia.NewGraph()
inputSize := len(vocab)
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithInit(gorgonia.GlorotN(1.0)))
// Объявляем переменные x и y с переменным размером батча, но жестким входным размером.
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))
losses := gorgonia.Must(gorgonia.Sub(yhatSig, y))
squaredLoss := gorgonia.Must(gorgonia.Square(losses))
loss := gorgonia.Must(gorgonia.Mean(squaredLoss))
_, err = gorgonia.Grad(loss, w)
if err != nil {
log.Fatalf("Failed to create gradients: %v", err)
}
optimizer := gorgonia.NewAdamSolver(gorgonia.WithLearnRate(0.001))
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
totalIterations := (totalSamples / batchSize) * numEpochs
currentIteration := 0
for epoch := 0; epoch < numEpochs; epoch++ {
var epochLoss float64
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)
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))
// Устанавливаем значения узлов, соответствующие текущему батчу
if err := xVal.Reshape(batchSizeActual, inputSize); err != nil {
log.Fatalf("Error reshaping xVal: %v", err)
}
if err := yVal.Reshape(batchSizeActual, 1); err != nil {
log.Fatalf("Error reshaping yVal: %v", err)
}
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)
}
lossData := loss.Value().Data()
lossVal, ok := lossData.(float32)
if !ok {
log.Fatalf("Unexpected type for loss value: %T", lossData)
}
epochLoss += float64(lossVal) * float64(batchSizeActual)
nodes := gorgonia.Nodes{w}
err = optimizer.Step(gorgonia.NodesToValueGrads(nodes))
if err != nil {
log.Fatalf("Error during optimizer step: %v", err)
}
machine.Reset()
runtime.GC()
currentIteration++
progressPercentage := float64(currentIteration) / float64(totalIterations) * 100
fmt.Printf("Progress: %.2f%%\r", progressPercentage)
}
averageLoss := epochLoss / float64(totalSamples)
fmt.Printf("Epoch %d/%d - Loss: %.4f\n", epoch+1, numEpochs, averageLoss)
}
fmt.Println("Model training complete")
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)
}
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))
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)
}
// 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()
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.")
}
}
Enter mode of operation (t for training, v for validation, d for dialogue): t
Loaded 10990 training records
2024/11/07 19:52:35 Error setting x value: Node's expected shape is (100, 14342). Got (90, 14342) instead
To resolve this error, you need to handle batches that do not perfectly divide the dataset size into equal parts. You can adjust the graph or code to accept variable batch sizes, especially for the last batch, which is often smaller. Here's how you can modify the code:
Modify the Code to Handle Last Batch Size
Adjust Graph Definition: Change the graph definition to accommodate variable batch sizes.
You currently define x and y with a static batch size. Instead, adjust these definitions to allow dynamic sizing:
// Instead of this:
// x := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(batchSize, inputSize), gorgonia.WithName("x"))
// Use this:
x := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, inputSize), gorgonia.WithName("x"))
y := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, 1), gorgonia.WithName("y"))
The use of -1 allows for dynamic batch sizing.
Reshape According to Current Batch: When setting up each batch, ensure x and y are reshaped for the current size:
With these adjustments, the shapes should match dynamically, preventing errors in setting tensor values in Gorgonia's tape machine.
Update Machine Configuration for Each Epoch: Inside your training loop, ensure reset between runs and reattach nodes if necessary (Gorgonia can handle node allocation efficiently).
Test with Varied Data: Once your code handles variable batch sizes, it's helpful to test with datasets of different sizes or configurations to ensure the flexibility of your implementation.
By implementing these changes, you should be able to handle the situation where the last batch is not full, thus correcting the mismatch error and proceeding through training correctly.
Вот полная реализация функции trainModel, которая обрабатывает различные размеры батчей и решает проблему несовпадения размеров:
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)
// Создаем директорию models, если она не существует
if err := os.MkdirAll("models", os.ModePerm); err != nil {
log.Fatalf("Error creating models directory: %v", err)
}
// Сохраняем словарь в директорию models
if err := SaveVocabulary(vocab, "models/vocab.gob"); err != nil {
log.Fatalf("Error saving vocabulary: %v", err)
}
totalSamples := len(parsedData)
numEpochs := 5
g := gorgonia.NewGraph()
inputSize := len(vocab)
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithInit(gorgonia.GlorotN(1.0)))
// Объявляем переменные x и y с переменным размером батча
x := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, inputSize), gorgonia.WithName("x"))
y := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, 1), gorgonia.WithName("y"))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
yhatSig := gorgonia.Must(gorgonia.Sigmoid(yhat))
losses := gorgonia.Must(gorgonia.Sub(yhatSig, y))
squaredLoss := gorgonia.Must(gorgonia.Square(losses))
loss := gorgonia.Must(gorgonia.Mean(squaredLoss))
_, err = gorgonia.Grad(loss, w)
if err != nil {
log.Fatalf("Failed to create gradients: %v", err)
}
optimizer := gorgonia.NewAdamSolver(gorgonia.WithLearnRate(0.001))
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
totalIterations := (totalSamples / batchSize) * numEpochs
currentIteration := 0
for epoch := 0; epoch < numEpochs; epoch++ {
var epochLoss float64
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)
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))
// Устанавливаем значения узлов, соответствующие текущему батчу
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)
}
lossData := loss.Value().Data()
lossVal, ok := lossData.(float32)
if !ok {
log.Fatalf("Unexpected type for loss value: %T", lossData)
}
epochLoss += float64(lossVal) * float64(batchSizeActual)
nodes := gorgonia.Nodes{w}
err = optimizer.Step(gorgonia.NodesToValueGrads(nodes))
if err != nil {
log.Fatalf("Error during optimizer step: %v", err)
}
machine.Reset()
runtime.GC()
currentIteration++
progressPercentage := float64(currentIteration) / float64(totalIterations) * 100
fmt.Printf("Progress: %.2f%%\r", progressPercentage)
}
averageLoss := epochLoss / float64(totalSamples)
fmt.Printf("Epoch %d/%d - Loss: %.4f\n", epoch+1, numEpochs, averageLoss)
}
fmt.Println("Model training complete")
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.")
}
}
Основные изменения:
Использование gorgonia.NewTensor с формой (-1, inputSize) для x и (-1, 1) для y, чтобы поддерживать динамическое изменение размера батча.
Удаление жесткого ограничения на размер батча в определении графа.
Корректная обработка последнего батча, который может быть не полного размера.
С такими изменениями модель сможет корректно обрабатывать последние неполные батчи, а также иметь гибкость в размере батча.
The error message Node's expected shape is (-1, 14342). Got (15, 14342) instead suggests that there is still a mismatch in the expected shape when setting the value of x. This typically occurs because Gorgonia expects a specific dynamic shape to have been previously established or that the setup didn’t account for batch variance properly.
Here’s how you can amend this to ensure proper dynamic batching will work:
Step-by-Step Solution
Dynamic Tensor Declaration:
Ensure that when declaring the placeholders (x and y), you're clearly specifying them as tensors capable of handling variable batch sizes.
x := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, inputSize), gorgonia.WithName("x"))
y := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, 1), gorgonia.WithName("y"))
Check Tensor Assignment:
When setting values during training, confirm to reshape tensors according to the batch’s actual size. Gorgonia requires the placeholder nodes to have input tensors that match the dimensions exactly, even for the dynamic parts.
// Before assigning, ensure the tensor is correctly shaped
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)
}
Multiple Runs and Machine Reset:
Reset the tape machine’s state between batches efficiently. Make sure to reset and clean up properly to avoid out-of-date assumptions about tensor shapes:
if err := machine.RunAll(); err != nil {
log.Fatalf("Machine run error during training: %v", err)
}
machine.Reset() // Reset after each batch
runtime.GC() // Optionally call GC, if needed
Tensor Setup During Initialization:
Update the tensor only after ensuring the batch’s dynamic parts are correctly sized.
Reconfirm Dynamic Placeholder Use:
Double-check to ensure that you're not inadvertently setting static sizes elsewhere which might conflict with dynamic batch handling.
Full Example
Let's modify the initial steps within trainModel() to ensure variable sizing works throughout:
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)
if err := os.MkdirAll("models", os.ModePerm); err != nil {
log.Fatalf("Error creating models directory: %v", err)
}
if err := SaveVocabulary(vocab, "models/vocab.gob"); err != nil {
log.Fatalf("Error saving vocabulary: %v", err)
}
totalSamples := len(parsedData)
numEpochs := 5
inputSize := len(vocab)
g := gorgonia.NewGraph()
w := gorgonia.NewMatrix(g, tensor.Float32, gorgonia.WithShape(inputSize, 1), gorgonia.WithInit(gorgonia.GlorotN(1.0)))
x := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, inputSize), gorgonia.WithName("x"))
y := gorgonia.NewTensor(g, tensor.Float32, 2, gorgonia.WithShape(-1, 1), gorgonia.WithName("y"))
yhat := gorgonia.Must(gorgonia.Mul(x, w))
yhatSig := gorgonia.Must(gorgonia.Sigmoid(yhat))
losses := gorgonia.Must(gorgonia.Sub(yhatSig, y))
squaredLoss := gorgonia.Must(gorgonia.Square(losses))
loss := gorgonia.Must(gorgonia.Mean(squaredLoss))
_, err = gorgonia.Grad(loss, w)
if err != nil {
log.Fatalf("Failed to create gradients: %v", err)
}
optimizer := gorgonia.NewAdamSolver(gorgonia.WithLearnRate(0.001))
machine := gorgonia.NewTapeMachine(g, gorgonia.BindDualValues(w))
defer machine.Close()
for epoch := 0; epoch < numEpochs; epoch++ {
var epochLoss float64
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)
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))
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)
}
lossData := loss.Value().Data().(float32)
epochLoss += float64(lossData) * float64(batchSizeActual)
nodes := gorgonia.Nodes{w}
if err := optimizer.Step(gorgonia.NodesToValueGrads(nodes)); err != nil {
log.Fatalf("Error during optimizer step: %v", err)
}
machine.Reset()
}
averageLoss := epochLoss / float64(totalSamples)
fmt.Printf("Epoch %d/%d - Loss: %.4f\n", epoch+1, numEpochs, averageLoss)
}
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.")
}
}