Esempio n. 1
0
func tensorData(c *C.TF_Tensor) []byte {
	// See: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
	cbytes := C.TF_TensorData(c)
	length := int(C.TF_TensorByteSize(c))
	slice := (*[1 << 30]byte)(unsafe.Pointer(cbytes))[:length:length]
	return slice
}
Esempio n. 2
0
// newTensorFromC converts from a C.TF_Tensor to a Tensor.
func newTensorFromC(ct *C.TF_Tensor) *Tensor {
	t := &Tensor{dt: DataType(C.TF_TensorType(ct))}
	numDims := int(C.TF_NumDims(ct))
	for i := 0; i < numDims; i++ {
		t.shape = append(t.shape, int64(C.TF_Dim(ct, C.int(i))))
	}
	b := make([]byte, int(C.TF_TensorByteSize(ct)))
	if len(b) > 0 {
		C.memcpy(unsafe.Pointer(&b[0]), C.TF_TensorData(ct), C.size_t(len(b)))
	}
	t.buf = bytes.NewBuffer(b)
	return t
}
Esempio n. 3
0
// Value converts the Tensor to a Go value. For now, not all Tensor types are
// supported, and this function may panic if it encounters an unsupported
// DataType.
//
// The type of the output depends on the Tensor type and dimensions.
// For example:
// Tensor(int64, 0): int64
// Tensor(float64, 3): [][][]float64
func (t *Tensor) Value() interface{} {
	typ, err := typeOf(t.DataType(), t.Shape())
	if err != nil {
		panic(err)
	}
	val := reflect.New(typ)
	// See: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
	cbytes := C.TF_TensorData(t.c)
	length := int(C.TF_TensorByteSize(t.c))
	slice := (*[1 << 30]byte)(unsafe.Pointer(cbytes))[:length:length]
	if err := decodeTensor(bytes.NewReader(slice), t.Shape(), typ, val); err != nil {
		panic(err)
	}
	return reflect.Indirect(val).Interface()
}