Skip to main content
 首页 » 编程设计

python之Tensorflow程序导致类型转换错误

2025年05月04日23jackei

尝试掌握 TensorFlow,遵循 TensorFlow 文档。

以下程序导致“不兼容的类型转换错误”

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]})) 

以上程序导致此错误

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'

我试图通过将“linear_model”变量定义为 float (linear_model = 1.0) 或 tf.to_float(linear_model = W * x + b) 来解决问题

但没有任何作用

我是 TensorFlow 新手,请帮助我。 提前致谢。

请您参考如下方法:

通过将其重铸为 float32,我能够让它运行。你读过图书馆的源代码吗?是的...我不问问题哈哈

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]}))