Tensorflow程序导致类型转换错误

时间:2017-06-07 00:03:06

标签: python machine-learning tensorflow

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

以上程序导致此错误

  

文件“v-prog3-variables.py”,第7行,in       linear_model = W * x + b   .. .. ..   ValueError:请求键入'float32'的不兼容类型转换   对于'int32_ref'类型的变量

我尝试通过将'linear_model'变量定义为float(linear_model = 1.0)或tf.to_float(linear_model = W * x + b)

来解决问题

但没有任何作用

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

2 个答案:

答案 0 :(得分:5)

我能够通过将它重铸到float32来运行它。你读过图书馆的源代码了吗?是的...我不问问题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]}))

答案 1 :(得分:3)

您需要为该类型使用命名参数,例如tf.Variable

__init__(self, initial_value=None, trainable=True,...的签名为__init__,导致常见错误。

[.3]方法将从您的输入中推断出类型:

  • tf.float32会提供[-3]
  • tf.int32会给tf.float32 导致你乘以它时得到的错误。

如果您想坚持使用[-3.]类型,您还可以使用b作为//Create a seperate js file named module.js in which add your code as below var testapp = angular.module("testApp",[]); testapp.controller("myCtrl",function ($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); //then inject module.js file below the angular.min.js and please make //angular.min.js locally because it won't work when you will offline 的初始值。