I have a list of doubles in scala and I want to convert it to constant for further processing , how would I go about that
By list, you mean a java.util.List
? If so, you need to convert your list to an array of primitive doubles then pass it to the Constant
op (or TFloat64
if you want to create a tensor that feeds a model). There are many ways of doing this. e.g. in Java,
Ops tf = Ops.create(...);
double[] array = list.stream().mapToDouble(x -> x).toArray();
Constant<TFloat64> constant = tf.constant(array);
try (TFloat64 tensor = TFloat64.vectorOf(array)) { ... }
Whenever possible, you should try to work directly with primitive types rather than their boxed type though (i.e. double
vs Double
), performance gains can be substantial.
i am using the java version in scala would you mind telling me the import I need
this is my code right now
var array_data = data.toArray
val constant_ = Constant(array_data)
the data is a list of Doubles
also sorry for the noob question i just started using scala 2 weeks ago thank you immensely for your help
No problem @ahmed_lone
Everything in the example I’ve provided is coming from the standard JDK (8+) and TensorFlow Java, nothing else should be required.
Oh you need to call tf.constant
, not Constant
directly.
import org.tensorflow.op.Ops;
import org.tensorflow.op.core.Constant;
Ops tf = Ops.create(); // this will use default eager session, but you might want to create a graph instead?
val test12: Constant[TFloat64] = tf.constant(array_data);
The Ops
instance is the entry point for creating all ops