This works fine:
import TensorFlow
var t = Tensor<Float>([[1, 0], [0, 1]])
But the following gives an error
import TensorFlow
var a = [[1, 0], [0, 1]]
var t = Tensor<Float>(a)
error: expression type 'Tensor<Float>' is ambiguous without more context
var t = Tensor<Float>(a)
^~~~~~~~~~~~~~~~
Why does this happen? Also how does one create a Tensor from arrays in swift.
Your first code works because it uses literals, as opposed to an already declared variable (whose type is already determined) to initialise the Tensor<Float>. Literals get special treatment by the compiler.
The overload of Tensor.init that you are calling is this. In your case, it accepts a ShapedArray<Float>.
ShapedArray conforms to the protocol ExpressibleByArrayLiteral, which means that the compiler can convert an array literal to ShapeArray implicitly. However, this is only limited to literals, such as [[1, 0], [0, 1]], not identifiers referring to a variable of an array type, such as a. a's type is inferred to be a [[Int]] by the compiler, and the compiler cannot implicitly convert a [[Int]] to ShapedArray<Float>.
Though less important, the fact that Float conforms to ExpressibleByIntegerLiteral (hence 1 and 0 can be converted to a float) also plays a role in allowing your code to compile.
The reason why var aa: Tensor<Float> = [[1.0, 0.0], [1.0, 0.0]] works is because Tensor also conforms to ExpressibleByArrayLiteral.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With