gotch/example/mnist/cnn.go

149 lines
3.5 KiB
Go
Raw Normal View History

2020-06-18 08:14:48 +01:00
package main
import (
"fmt"
2020-06-22 16:07:07 +01:00
"log"
2020-06-23 10:14:08 +01:00
"time"
2020-06-22 16:07:07 +01:00
"github.com/sugarme/gotch"
"github.com/sugarme/gotch/nn"
2022-03-12 07:20:20 +00:00
"github.com/sugarme/gotch/ts"
2020-06-22 16:07:07 +01:00
"github.com/sugarme/gotch/vision"
)
const (
MnistDirCNN string = "../../data/mnist"
2020-06-23 10:14:08 +01:00
epochsCNN = 100
2020-06-22 16:07:07 +01:00
batchCNN = 256
2020-06-23 10:14:08 +01:00
batchSize = 256
2020-06-22 16:07:07 +01:00
LrCNN = 1e-4
2020-06-18 08:14:48 +01:00
)
2020-06-22 16:07:07 +01:00
type Net struct {
conv1 *nn.Conv2D
conv2 *nn.Conv2D
fc1 *nn.Linear
fc2 *nn.Linear
2020-06-22 16:07:07 +01:00
}
func newNet(vs *nn.Path) *Net {
2020-06-22 16:07:07 +01:00
conv1 := nn.NewConv2D(vs, 1, 32, 5, nn.DefaultConv2DConfig())
conv2 := nn.NewConv2D(vs, 32, 64, 5, nn.DefaultConv2DConfig())
fc1 := nn.NewLinear(vs, 1024, 1024, nn.DefaultLinearConfig())
fc2 := nn.NewLinear(vs, 1024, 10, nn.DefaultLinearConfig())
2020-06-22 16:07:07 +01:00
return &Net{
2020-06-22 16:07:07 +01:00
conv1,
conv2,
fc1,
fc2}
2020-06-22 16:07:07 +01:00
}
func (n *Net) ForwardT(xs *ts.Tensor, train bool) *ts.Tensor {
2020-06-23 10:14:08 +01:00
outView1 := xs.MustView([]int64{-1, 1, 28, 28}, false)
defer outView1.MustDrop()
outC1 := outView1.Apply(n.conv1)
outMP1 := outC1.MaxPool2DDefault(2, true)
defer outMP1.MustDrop()
outC2 := outMP1.Apply(n.conv2)
outMP2 := outC2.MaxPool2DDefault(2, true)
outView2 := outMP2.MustView([]int64{-1, 1024}, true)
defer outView2.MustDrop()
outFC1 := outView2.Apply(n.fc1)
2020-06-23 10:14:08 +01:00
outRelu := outFC1.MustRelu(true)
defer outRelu.MustDrop()
outDropout := ts.MustDropout(outRelu, 0.5, train)
defer outDropout.MustDrop()
return outDropout.Apply(n.fc2)
2020-06-22 16:07:07 +01:00
}
2020-06-23 16:37:33 +01:00
func runCNN1() {
2020-06-22 16:07:07 +01:00
var ds *vision.Dataset
2020-06-22 16:07:07 +01:00
ds = vision.LoadMNISTDir(MnistDirNN)
2022-03-12 04:47:15 +00:00
// ds.TrainImages [60000, 784]
// ds.TrainLabels [60000, 784]
testImages := ds.TestImages // [10000, 784]
testLabels := ds.TestLabels // [10000, 784]
fmt.Printf("testImages: %v\n", testImages.MustSize())
fmt.Printf("testLabels: %v\n", testLabels.MustSize())
2020-06-23 16:37:33 +01:00
device := gotch.CudaIfAvailable()
vs := nn.NewVarStore(device)
net := newNet(vs.Root())
opt, err := nn.DefaultAdamConfig().Build(vs, LrCNN)
2020-06-22 16:07:07 +01:00
if err != nil {
log.Fatal(err)
}
var bestAccuracy float64 = 0.0
2020-06-23 10:14:08 +01:00
startTime := time.Now()
2020-06-22 16:07:07 +01:00
for epoch := 0; epoch < epochsCNN; epoch++ {
2020-06-23 10:14:08 +01:00
totalSize := ds.TrainImages.MustSize()[0]
samples := int(totalSize)
2022-03-12 04:47:15 +00:00
// Shuffling
2020-06-23 16:37:33 +01:00
index := ts.MustRandperm(int64(totalSize), gotch.Int64, gotch.CPU)
imagesTs := ds.TrainImages.MustIndexSelect(0, index, false)
labelsTs := ds.TrainLabels.MustIndexSelect(0, index, false)
2022-03-12 04:47:15 +00:00
index.MustDrop()
2020-06-23 10:14:08 +01:00
batches := samples / batchSize
batchIndex := 0
2022-03-12 04:47:15 +00:00
var epocLoss float64
2020-06-23 10:14:08 +01:00
for i := 0; i < batches; i++ {
start := batchIndex * batchSize
size := batchSize
if samples-start < batchSize {
2020-06-22 16:07:07 +01:00
break
}
2020-06-23 10:14:08 +01:00
batchIndex += 1
// Indexing
2022-03-12 04:47:15 +00:00
bImages := imagesTs.MustNarrow(0, int64(start), int64(size), false)
bLabels := labelsTs.MustNarrow(0, int64(start), int64(size), false)
2020-06-23 10:14:08 +01:00
bImages = bImages.MustTo(vs.Device(), true)
bLabels = bLabels.MustTo(vs.Device(), true)
logits := net.ForwardT(bImages, true)
2022-03-12 04:47:15 +00:00
bImages.MustDrop()
2020-06-23 10:14:08 +01:00
loss := logits.CrossEntropyForLogits(bLabels)
2022-03-12 04:47:15 +00:00
logits.MustDrop()
bLabels.MustDrop()
2020-06-22 16:07:07 +01:00
2022-03-12 04:47:15 +00:00
loss = loss.MustSetRequiresGrad(true, true)
2020-06-22 16:07:07 +01:00
opt.BackwardStep(loss)
2020-06-23 10:14:08 +01:00
2022-03-12 04:47:15 +00:00
epocLoss = loss.Float64Values()[0]
loss.MustDrop()
2020-06-22 16:07:07 +01:00
}
2022-03-12 04:47:15 +00:00
ts.NoGrad(func() {
testAccuracy := nn.BatchAccuracyForLogits(vs, net, testImages, testLabels, vs.Device(), 1024)
fmt.Printf("Epoch: %v\t Loss: %.2f \t Test accuracy: %.2f%%\n", epoch, epocLoss, testAccuracy*100.0)
if testAccuracy > bestAccuracy {
bestAccuracy = testAccuracy
}
})
2020-06-23 10:14:08 +01:00
2020-06-23 16:37:33 +01:00
imagesTs.MustDrop()
labelsTs.MustDrop()
}
fmt.Printf("Best test accuracy: %.2f%%\n", bestAccuracy*100.0)
2020-06-23 10:14:08 +01:00
fmt.Printf("Taken time:\t%.2f mins\n", time.Since(startTime).Minutes())
2020-06-18 08:14:48 +01:00
}