-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtensor.go
More file actions
93 lines (80 loc) · 1.8 KB
/
tensor.go
File metadata and controls
93 lines (80 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package gotensor
import (
"bytes"
"encoding/gob"
tf "github.com/tensorflow/tensorflow/tensorflow/go"
)
// Tensor is a TensorFlow tensor that satisfies the GobDecoder and the
// GobEncode interface.
type Tensor struct {
*tf.Tensor
}
// GobDecode overwrites the receiver, which must be a pointer, with
// the value represented by the byte slice, which was written by
// GobEncode, usually for the same concrete type.
func (t *Tensor) GobDecode(b []byte) error {
r := bytes.NewReader(b)
dec := gob.NewDecoder(r)
var dt tf.DataType
err := dec.Decode(&dt)
if err != nil {
return err
}
var shape []int64
err = dec.Decode(&shape)
if err != nil {
return err
}
var tensor *tf.Tensor
switch dt {
case tf.String:
// TensorFlow Go package currently does not support
// string serialization. Let's do it ourselves.
var str string
err = dec.Decode(&str)
if err != nil {
return err
}
tensor, err = tf.NewTensor(str)
if err != nil {
return err
}
default:
tensor, err = tf.ReadTensor(dt, shape, r)
if err != nil {
return err
}
}
t.Tensor = tensor
return nil
}
// GobEncode returns a byte slice representing the encoding of the
// receiver for transmission to a GobDecoder, usually of the same
// concrete type.
func (t Tensor) GobEncode() ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(t.DataType())
if err != nil {
return nil, err
}
err = enc.Encode(t.Shape())
if err != nil {
return nil, err
}
switch t.DataType() {
case tf.String:
// TensorFlow Go package currently does not support
// string serialization. Let's do it ourselves.
err = enc.Encode(t.Tensor.Value().(string))
if err != nil {
return nil, err
}
default:
_, err = t.WriteContentsTo(&buf)
if err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}