NewTensor converts from a Go value to a Tensor. Valid values are scalars, slices, and arrays. Every element of a slice must have the same length so that the resulting Tensor has a valid shape.
(value interface{})
| 70 | // slices, and arrays. Every element of a slice must have the same length so |
| 71 | // that the resulting Tensor has a valid shape. |
| 72 | func NewTensor(value interface{}) (*Tensor, error) { |
| 73 | val := reflect.ValueOf(value) |
| 74 | shape, dataType, err := shapeAndDataTypeOf(val) |
| 75 | if err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | nflattened := numElements(shape) |
| 79 | nbytes := typeOf(dataType, nil).Size() * uintptr(nflattened) |
| 80 | if dataType == String { |
| 81 | // TF_STRING tensors are encoded as an array of 8-byte offsets |
| 82 | // followed by string data. See c_api.h. |
| 83 | nbytes = uintptr(nflattened*8) + byteSizeOfEncodedStrings(value) |
| 84 | } |
| 85 | var shapePtr *C.int64_t |
| 86 | if len(shape) > 0 { |
| 87 | shapePtr = (*C.int64_t)(unsafe.Pointer(&shape[0])) |
| 88 | } |
| 89 | t := &Tensor{ |
| 90 | c: C.TF_AllocateTensor(C.TF_DataType(dataType), shapePtr, C.int(len(shape)), C.size_t(nbytes)), |
| 91 | shape: shape, |
| 92 | } |
| 93 | runtime.SetFinalizer(t, (*Tensor).finalize) |
| 94 | raw := tensorData(t.c) |
| 95 | buf := bytes.NewBuffer(raw[:0:len(raw)]) |
| 96 | if dataType != String { |
| 97 | if err := encodeTensor(buf, val, shape); err != nil { |
| 98 | return nil, err |
| 99 | } |
| 100 | if uintptr(buf.Len()) != nbytes { |
| 101 | return nil, bug("NewTensor incorrectly calculated the size of a tensor with type %v and shape %v as %v bytes instead of %v", dataType, shape, nbytes, buf.Len()) |
| 102 | } |
| 103 | } else { |
| 104 | e := stringEncoder{offsets: buf, data: raw[nflattened*8:], status: newStatus()} |
| 105 | if err := e.encode(reflect.ValueOf(value), shape); err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | if int64(buf.Len()) != nflattened*8 { |
| 109 | return nil, bug("invalid offset encoding for TF_STRING tensor with shape %v (got %v, want %v)", shape, buf.Len(), nflattened*8) |
| 110 | } |
| 111 | } |
| 112 | return t, nil |
| 113 | } |
| 114 | |
| 115 | // ReadTensor constructs a Tensor with the provided type and shape from the |
| 116 | // serialized tensor contents in r. |