1 发现问题
利用TensorFlow框架进行自实现线性回归时,报错:TypeError: Input ‘b’ of ‘MatMul’ Op has type int32 that does not match type float32 of argument ‘a’.
 
   
源代码:    
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | def liner_regression():
 自实现一个线性回归
 y_true = 0.8X + 0.7
 :return:
 
 # 1 准备数据
 X = tf.random_normal(shape=[100, 1],mean=0.0,stddev=1.0,name="feature") # 用高斯分布生成随机值,
 y_true =  tf.matmul( X, [[8]]) + 0.7 # 用高斯分布生成随机值, 默认均值是0 方差是1
 
 # 2 构造模型
 # 模型构造用TensorFlow中的变量进行定义
 # 2.1 weights
 weights = tf.Variable(initial_value=tf.random_normal(shape=[1,1]),name="weights")
 # 2.2 bias
 bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]),name="bias")
 # 2.3 构建模型
 y_predict = tf.matmul(X,weights) + bias
 
 # 3 构造损失函数
 # loss = tf.reduce_mean(tf.square(y_predict - y_true))
 
 # 4 优化损失 梯度下降算法
 # optimaizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
 
 # 显式的初始化变量
 init = tf.global_variables_initializer()
 
 # 开启会话
 with tf.Session() as sess:
 sess.run(init)
 print(X)
 print(weights)
 print(bias)
 
 | 
2 解决问题
问题代码:   
| 12
 
 | X = tf.random_normal(shape=[100, 1],mean=0.0,stddev=1.0,name="feature") # 用高斯分布生成随机值,y_true =  tf.matmul( X, [[8]]) + 0.7 # 用高斯分布生成随机值, 默认均值是0 方差是1
 
 | 

修改建议:
将y_true =  tf.matmul( X, [[8]]) + 0.7中的[[8]]改成[[8.0]]或者使用tf.cast([[8]],tf.float32)进行数据类型转换
写在最后
欢迎大家关注鄙人的公众号【麦田里的守望者zhg】,让我们一起成长,谢谢。
