在学习tensorflow的过程中,因为不熟悉python和tensorflow,导致许多错误可能寻找起来非常困难,今天的学习中出现了这样一个错误:
TypeError: Input ‘b’ of ‘MatMul’ Op has type float32 that does not match type float64 of argument ‘a’.
程序代码:
import tensorflow as tf
import numpy as np
def add_layer(inputs,in_size,out_size,activation_function = None):
Weights = tf.Variable(tf.random_normal([in_size,out_size]),dtype=tf.float32)
biases = tf.Variable(tf.zeros([1,out_size])+0.1,dtype=tf.float32)
Wx_plus_b= tf.matmul(inputs,Weights)+biases
#tf.cast(inputs,tf.float32)
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
x_data = np.linspace(-1,1,300)[:,np.newaxis]
noise = np.random.normal(0,0.05,x_data.shape)
y_data = np.square(x_data)-0.5+noise
xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])
l1 = add_layer(x_data,1,10,activation_function=tf.nn.relu)
prediction = add_layer(l1,10,1,activation_function=None)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(1000):
sess.run(train_step ,feed_dict={xs:x_data,ys:y_data})
if i % 50==0:
print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
虽然能看到错误类型是乘法函数tf.matmul()两端数据类型不一致造成的,但是还是找了许久,思量许久后我推测是由于 np.linspace()函数造出来的随机数是float64的所造成的错误,真是奇怪了,我的代码是和教程里的一模一样的,为什么会这样呢,于是我在matmul()函数的第一个输入值加了类型转换tf.cast(inputs,tf.float32),问题解决了.