Other things from the previous chapter

Obviously, there is a lot from the previous chapter that we can reuse:

  • The range normalization function (pixelWeight) and its isometric counterpart (reversePixelWeight)
  • prepareX and prepareY
  • The visualize function

For convenience sake, here they are again:

func pixelWeight(px byte) float64 {
retVal := (float64(px) / 255 * 0.999) + 0.001
if retVal == 1.0 {
return 0.999
}
return retVal
}
func reversePixelWeight(px float64) byte {
return byte(((px - 0.001) / 0.999) * 255)
}
func prepareX(M []RawImage) (retVal tensor.Tensor) {
rows := len(M)
cols := len(M[0])

b := make([]float64, 0, rows*cols)
for i := 0; i < rows; i++ {
for j := 0; j < len(M[i]); j++ {
b = append(b, pixelWeight(M[i][j]))
}
}
return tensor.New(tensor.WithShape(rows, cols), tensor.WithBacking(b))
}
func prepareY(N []Label) (retVal tensor.Tensor) {
rows := len(N)
cols := 10

b := make([]float64, 0, rows*cols)
for i := 0; i < rows; i++ {
for j := 0; j < 10; j++ {
if j == int(N[i]) {
b = append(b, 0.999)
} else {
b = append(b, 0.001)
}
}
}
return tensor.New(tensor.WithShape(rows, cols), tensor.WithBacking(b))
}
func visualize(data tensor.Tensor, rows, cols int, filename string) (err error) {
N := rows * cols

sliced := data
if N > 1 {
sliced, err = data.Slice(makeRS(0, N), nil) // data[0:N, :] in python
if err != nil {
return err
}
}

if err = sliced.Reshape(rows, cols, 28, 28); err != nil {
return err
}

imCols := 28 * cols
imRows := 28 * rows
rect := image.Rect(0, 0, imCols, imRows)
canvas := image.NewGray(rect)

for i := 0; i < cols; i++ {
for j := 0; j < rows; j++ {
var patch tensor.Tensor
if patch, err = sliced.Slice(makeRS(i, i+1), makeRS(j,
j+1)); err != nil {
return err
}

patchData := patch.Data().([]float64)
for k, px := range patchData {
x := j*28 + k%28
y := i*28 + k/28
c := color.Gray{reversePixelWeight(px)}
canvas.Set(x, y, c)
}
}
}

var f io.WriteCloser
if f, err = os.Create(filename); err != nil {
return err
}

if err = png.Encode(f, canvas); err != nil {
f.Close()
return err
}

if err = f.Close(); err != nil {
return err
}
return nil
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.164.24