I am trying to use a TensorFlow model in Go. Frankly, I know nothing about Machine learning. I am just trying to run the model. I've been successful so far by doing as below
func (m *Engine) Run(ctx context.Context, r io.Reader, resizType bool) (probability float64, err error) {
// Create a session for inference over graph.
session, err := tf.NewSession(m.model, nil)
if err != nil {
log.Fatal(err)
}
defer session.Close()
tensor, err := makeTensorFromImage(ctx, r, resizType)
if err != nil {
return 0, err
}
output, err := session.Run(
map[tf.Output]*tf.Tensor{
m.model.Operation("model_2_input").Output(0): tensor,
},
[]tf.Output{
m.model.Operation("dense_4/Sigmoid").Output(0),
},
nil)
if err != nil {
fmt.Println(err)
}
probabilities := output[0].Value().([][]float32)[0]
return float64(probabilities[0]), nil
}
func makeTensorFromImage(ctx context.Context, image io.Reader, resizType bool) (*tf.Tensor, error) {
bytes := StreamToByte(image)
tensor, err := tf.NewTensor(string(bytes))
if err != nil {
return nil, err
}
// Construct a graph to normalize the image
graph, input, output, err := constructGraphToNormalizeImage(resizType)
if err != nil {
return nil, err
}
// Execute that graph to normalize this one image
session, err := tf.NewSession(graph, nil)
if err != nil {
return nil, err
}
defer session.Close()
normalized, err := session.Run(
map[tf.Output]*tf.Tensor{input: tensor},
[]tf.Output{output},
nil)
if err != nil {
return nil, err
}
return normalized[0], nil
}
The below func give me a graph of shape [1,224,224,3] .
func constructGraphToNormalizeImage(resizType bool) (graph *tf.Graph, input, output tf.Output, err error) {
const (
H, W = 224, 224
Mean = float32(0)
Scale = float32(255)
)
s := op.NewScope()
input = op.Placeholder(s, tf.String)
if resizType {
output = op.Div(s,
op.Sub(s,
op.ResizeArea(s,
op.ExpandDims(s,
op.Cast(s,
op.DecodeJpeg(s, input, op.DecodeJpegChannels(3)), tf.Float),
op.Const(s.SubScope("make_batch"), int32(0))),
op.Const(s.SubScope("size"), []int32{H, W})),
op.Const(s.SubScope("mean"), Mean)),
op.Const(s.SubScope("scale"), Scale))
graph, err = s.Finalize()
} else {
output = op.Div(s,
op.Sub(s,
op.ResizeNearestNeighbor(s,
op.ExpandDims(s,
op.Cast(s,
op.DecodeJpeg(s, input, op.DecodeJpegChannels(3)), tf.Float),
op.Const(s.SubScope("make_batch"), int32(0))),
op.Const(s.SubScope("size"), []int32{H, W})),
op.Const(s.SubScope("mean"), Mean)),
op.Const(s.SubScope("scale"), Scale))
graph, err = s.Finalize()
}
return graph, input, output, err
}
Now I don't want to use any resize function of any kind. I tried removing the resize func bit it gives me a shape of [1,?,?,3] obviously. So my question is how do I achieve what I need without resizing.