You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow运行MNIST测试时出现数据类型转换错误求助

Fix for ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32 in TensorFlow Leaky ReLU

Hey there, let's get this error sorted out right away! The core issue here is integer division behavior in Python 2.7—since you're using Python 2, the expression 1/3 evaluates to 0 (an int32 integer), but your input tensor conv2d(x_image, W_conv1) + b_conv1 is of type float32. TensorFlow throws this mismatch error because it can't safely convert your floating-point tensor to integer type for the Leaky ReLU operation.

Quick Fixes

You just need to force float division instead of integer division for the alpha parameter. Pick one of these options:

  • Use a float literal in the division: alpha=1.0/3
  • Or swap the float literal: alpha=1/3.0
  • Or explicitly cast to float: alpha=float(1)/3

Your corrected line will look like this:

h_conv1 = tf.nn.leaky_relu(conv2d(x_image, W_conv1) + b_conv1, alpha=1.0/3)

Why This Happened

In Python 2, dividing two integers with / does floor division (truncates the result to the nearest integer), so 1/3 becomes 0 (an int32 value). TensorFlow's tf.nn.leaky_relu expects the alpha value to match the data type of the input tensor. When you pass an int32 alpha with a float32 tensor, it tries to convert the tensor to int32—which fails because your tensor contains floating-point values that can't be represented as integers.

If you want to avoid this kind of issue long-term, add from __future__ import division at the very top of your script. This makes Python 2 use Python 3-style float division for all / operations, so 1/3 will evaluate to 0.333... instead of 0.

内容的提问来源于stack exchange,提问作者Leo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:37:10