class2 week3 3.11 practice
在本节课的视频中,吴恩达老师向我们展示了如何利用tensorflow框架进行简单的运算,其中有一段代码:
w = tf.Variable(0, dtype=tf.float32)
# cause we can not add more than 2 object with tf.add
# so we have to use double tf.add to realize it
cost = tf.add(tf.add(w**2, tf.multiply(tf.cast(-10, tf.float32), w)), 25)
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
print(sess.run(w))
运行时报错:
TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type int32 of argument 'x'+
类似的错误还有
TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a
其实就是tensorflow下的乘法不允许不同类型的数据相乘,比如w之前设定的是tf.float32,但是和他相乘的-10是int类型的,所以这里需要转换一下,就用到了一个函数:tf.cast()
将原代码种出错的部分改为:
cost = tf.add(tf.add(w**2, tf.multiply(tf.cast(-10, tf.float32), w)), 25)
另外还需要注意,tf.add()只能将两个对象相加,如果有三个对象,需要再一次调用tf.add()
当然,稍后,吴恩达老师又介绍了一种表达cost func的方法:
直接利用普通的加减运算,此时就不要再将对象处理成同类型的了
参考自:TypeError: Input ‘b’ of ‘MatMul’ Op has type float32 that does not match type float64 of argument 'a