在 Python 深度学习(如 TensorFlow、PyTorch、Keras 等)开发中,初学者和有一定经验的开发者都容易踩坑。下面按常见类型总结常见错误、原因和解决办法。
表现
CUDA not available原因
解决
nvidia-smi
python -c "import torch; print(torch.cuda.is_available())"
确保:
表现
module 'keras' has no attribute 'X'解决
pip install tensorflow==2.13.0
表现
ValueError: expected input shape (None, 28, 28, 1), got (None, 28, 28)
原因
解决
x = x.reshape(-1, 28, 28, 1)
表现
TypeError: Expected float32 but got int64
解决
x = x.astype('float32') / 255.0
y = y.astype('int64')
常见错误
解决
# 二分类
model.compile(loss='binary_crossentropy')
# 多分类
from keras.utils import to_categorical
y = to_categorical(y, num_classes=10)
表现
The shape of the input to "Flatten" is not compatible
原因
正确示例
model.add(Conv2D(32, (3,3), activation='relu'))
model.add(Flatten())
model.add(Dense(10))
常见错误
正确选择
| 任务 | 输出层 |
|---|---|
| 二分类 | sigmoid |
| 多分类 | softmax |
| 回归 | linear |
表现
原因
解决
optimizer = Adam(learning_rate=1e-4)
使用 BatchNorm、LayerNorm。
表现
解决
EarlyStopping(patience=5)
PyTorch 特有
model.train()
model.eval()
否则 Dropout / BatchNorm 行为错误。
x += y # 错误
x = x + y # 正确
x.numpy() # 必须在 CPU
或使用:
x.detach().cpu().numpy()
✅ 从小数据开始
✅ 先跑通 1–2 个 batch
✅ 打印 shape / dtype
✅ 使用 model.summary()
✅ 用 torchinfo / keras.utils.plot_model
如果你愿意,我可以:
你可以直接把错误贴出来。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。