Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow program results in type conversion error

Tring to master Tensorflow, following documentation of TensorFlow.

Below program results in 'Incompatible type conversion error'

import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = 1.0
linear_model = W * x + b
#tf.to_float(linear_model, name='ToFloat')

# Global initialization is must
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))

Above program results in this error

File "v-prog3-variables.py", line 7, in linear_model = W * x + b .. .. .. ValueError: Incompatible type conversion requested to type 'float32' for variable of type 'int32_ref'

I tried to solve the problem by defining the 'linear_model' variable as float (linear_model = 1.0) or tf.to_float(linear_model = W * x + b)

but nothing works

Im a TensorFlow newbie, please help me out. Thanks in advance.

like image 276
Vikram Avatar asked Mar 25 '26 19:03

Vikram


2 Answers

I was able to get it to run by recasting it to float32. Have you read the source code of the library? Yea... I don't ask questions lol

import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)

linear_model = W * x + tf.cast(b, tf.float32)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))
like image 120
Alex Konrad Keßler Avatar answered Mar 28 '26 09:03

Alex Konrad Keßler


You need to use a named argument for the type, e.g. tf.Variable([.3], dtype=tf.float32)

The signature of tf.Variable is __init__(self, initial_value=None, trainable=True,... leading to common errors.

The __init__ method will then infer type from your inputs:

  • [.3] will give a tf.float32, and
  • [-3] will give a tf.int32 leading to the error you got when you multiply them.

If you want to stick with the tf.float32 type, you could also use [-3.] as initial value for b.

like image 36
pfm Avatar answered Mar 28 '26 08:03

pfm