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

Colab训练Unet模型遇keras.api.backend无clip属性错误求解决

解决AttributeError: module 'keras.api.backend' has no attribute 'clip'错误

问题背景

在Colab中使用segmentation_models库训练Unet模型时,训练第一个epoch触发以下错误,已尝试升级TensorFlow和Keras但无效:

AttributeError: module 'keras.api.backend' has no attribute 'clip'.

相关代码

import segmentation_models as sm
model_vgg16=sm.Unet(backbone_name=backbone,input_shape=(256,256,3),classes=4,activation="softmax",encoder_weights="imagenet",decoder_use_batchnorm=True,encoder_freeze=False )

model_vgg16.summary()

"""# loss and metrics"""

loss="categorical_crossentropy"

dice_loss=sm.losses.DiceLoss()
focal_loss=sm.losses.CategoricalFocalLoss()

focal_dice_loss=sm.losses.categorical_focal_dice_loss

metric=[sm.metrics.IOUScore(threshold=0.5)]

"""# compile"""

lr=0.001
model_vgg16.compile(optimizer=keras.optimizers.Adam(learning_rate=lr),
              loss=[focal_dice_loss],
              metrics=[metric])

history = model_vgg16.fit(preprocessed_x_train, ytrain_categorical, epochs=20,validation_data=(preprocessed_x_val,y_val_categorical),batch_size=32)

错误详情

Epoch 1/20
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-76-887dcd97e6be> in <cell line: 1>()
----> 1 history = model_vgg16.fit(preprocessed_x_train, ytrain_categorical, epochs=20,
      2                     validation_data=(preprocessed_x_val,y_val_categorical),
      3                     batch_size=32)

3 frames
/usr/local/lib/python3.10/dist-packages/segmentation_models/base/functional.py in categorical_focal_loss(gt, pr, gamma, alpha, class_indexes, **kwargs)
    276 
    277     # clip to prevent NaN's and Inf's
--> 278     pr = backend.clip(pr, backend.epsilon(), 1.0 - backend.epsilon())
    279 
    280     # Calculate focal loss

AttributeError: module 'keras.api.backend' has no attribute 'clip'

解决方案

错误根源是segmentation_models旧版本不兼容Keras 3.x,新版Keras已移除backend.clip接口,替换为tf.clip_by_value或keras.ops.clip。提供三种可行解决方法:

方法1:降级Keras到兼容版本

在Colab中执行以下命令,将Keras降级至2.x稳定版本:

!pip install keras==2.15.0

执行后重启Colab运行时,重新运行代码即可。

方法2:临时修改库源码

找到报错文件/usr/local/lib/python3.10/dist-packages/segmentation_models/base/functional.py,将第278行的:

pr = backend.clip(pr, backend.epsilon(), 1.0 - backend.epsilon())

替换为:

import tensorflow as tf
pr = tf.clip_by_value(pr, backend.epsilon(), 1.0 - backend.epsilon())

此方法无需降级,但库更新后修改会被覆盖,适合临时应急。

方法3:安装适配Keras 3.x的分支版本

如果需要保留Keras 3.x,可尝试安装项目的适配分支:

!pip install git+https://github.com/qubvel/segmentation_models.git@keras-3

注意:该分支处于开发阶段,稳定性需自行测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:53:15