美文网首页
TensorFlow 遇到的MatMul bug

TensorFlow 遇到的MatMul bug

作者: 沐一川 | 来源:发表于2017-11-22 10:18 被阅读0次

    python版本             3.6.3

    TensorFlow版本     1.2.1

    用写TensorFlow的时候出现了一个bug:

    TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a'.

    数据类型错误:MatMul里输入的数据类型为‘float32’的‘b’无法和数据类型为‘float64’的‘a’匹配。

    1.看一下添加层内部matmul里的情况:

    Wx_plus_b = tf.matmul(inputs,Weights) + biases

    2.那么inputs应该就是底层实现里的‘a’,Weights为‘b’,

    沿着参数传递找到数据源头:

    x_data = np.linspace(-1,1,300)[:,np.newaxis]

    3.在代码后方加入一个类型转换:

    x_data = np.linspace(-1,1,300)[:,np.newaxis].astype('float32')

    F5

    Well done.

    源码:

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

        biases = tf.Variable(tf.zeros([1,out_size])+0.1)

        Wx_plus_b = tf.matmul(inputs,Weights) + biases

        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()

    #会话控制

    sess = tf.Session()

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

    相关文章

      网友评论

          本文标题:TensorFlow 遇到的MatMul bug

          本文链接:https://www.haomeiwen.com/subject/uyhnvxtx.html