ValueError: Invalid type tf.int32 for Mean_7:0, expected: [tf.float32, tf.float64, tf.float16].

错误原因:
ValueError: Invalid type tf.int32 for Mean_7:0, expected: [tf.float32, tf.float64, tf.float16]._第1张图片
图中初始化b和k的时候只写了0,应该是0.
因为tf其他包要求是float32或者float64的类型
ValueError: Invalid type tf.int32 for Mean_7:0, expected: [tf.float32, tf.float64, tf.float16].
ValueError: Invalid type tf.int32 for Mean_7:0, expected: [tf.float32, tf.float64, tf.float16]._第2张图片

代码如下:

import tensorflow as tf
import numpy as np
#使用numpy生成100个随机点
x_data = np.random.rand(100)
y_data = x_data * 0.1 + 0.2

#构造一个线性模型
b = tf.Variable(0)
k = tf.Variable(0)
y = k * x_data + b

#二次代价函数
loss = tf.reduce_mean(tf.square(y_data - y))
#定义一个梯度下降算法来进行训练的优化器
optimizer = tf.train.GradientDescentOptimizer(0.2)
#最小化代价函数
train = optimizer.minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for step in range(201):
        sess.run(train)
        if step % 20 == 0:
            print(step,sess.run([k,b]))

报错如下:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-fe18d1ec80d8> in <module>()
     13 optimizer = tf.train.GradientDescentOptimizer(0.2)
     14 #最小化代价函数
---> 15 train = optimizer.minimize(loss)
     16 
     17 #初始化变量

D:\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py in minimize(self, loss, global_step, var_list, gate_gradients, aggregation_method, colocate_gradients_with_ops, name, grad_loss)
    313         aggregation_method=aggregation_method,
    314         colocate_gradients_with_ops=colocate_gradients_with_ops,
--> 315         grad_loss=grad_loss)
    316 
    317     vars_with_grad = [v for g, v in grads_and_vars if g is not None]

D:\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py in compute_gradients(self, loss, var_list, gate_gradients, aggregation_method, colocate_gradients_with_ops, grad_loss)
    364                        "Optimizer.GATE_OP, Optimizer.GATE_GRAPH.  Not %s" %
    365                        gate_gradients)
--> 366     self._assert_valid_dtypes([loss])
    367     if grad_loss is not None:
    368       self._assert_valid_dtypes([grad_loss])

D:\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py in _assert_valid_dtypes(self, tensors)
    515         raise ValueError(
    516             "Invalid type %r for %s, expected: %s." % (
--> 517                 dtype, t.name, [v for v in valid_dtypes]))
    518 
    519   # --------------

ValueError: Invalid type tf.int32 for Mean_7:0, expected: [tf.float32, tf.float64, tf.float16].

你可能感兴趣的:(tensorflow挖坑,tensorflow)