Databricks Notebook无法导入sparkdl模块的版本兼容问题求助
解决方案:Databricks中SparkDL导入错误(resnet50找不到)
问题根源
旧版spark-deep-learning(如1.4.0)仅适配TensorFlow 1.x,而你使用的TensorFlow 2.5.0自带的tf.keras与独立安装的Keras 2.2.4存在冲突,且SparkDL的导入逻辑依赖旧版Keras的模块路径,导致无法找到resnet50。
方案1:使用TF2兼容的SparkDL版本(推荐)
版本组合调整
- 移除独立Keras,使用TensorFlow 2.5.0自带的
tf.keras - Maven库改用支持TF2的SparkDL版本:
databricks:spark-deep-learning:2.0.0-spark3.0-s_2.12(根据你的Spark版本匹配,Spark 3.1对应2.1.0,Spark 3.2对应2.2.0) - PyPI依赖:
tensorflow==2.5.0、h5py==3.1.0(与TF2.5兼容,避免高版本h5py的兼容性问题)
操作步骤
- 进入Databricks集群的库管理页面
- 删除已安装的独立Keras库
- 添加Maven库,填入上述坐标
- 添加PyPI库,分别指定
tensorflow==2.5.0和h5py==3.1.0 - 重启集群后,在Notebook中执行:
import tensorflow as tf from sparkdl import DeepImageFeaturizer, readImages
方案2:临时修复导入路径(不推荐长期使用)
如果无法更换SparkDL版本,可在Notebook中手动修正模块导入逻辑,绕过路径冲突:
import sys # 手动导入resnet50模块并注册到系统模块中 from keras.applications import resnet50 sys.modules['keras.applications.resnet50'] = resnet50 # 再导入SparkDL模块 from sparkdl import DeepImageFeaturizer
注意:此方法仅解决导入问题,后续可能出现其他TF2与旧版SparkDL的兼容性错误。
方案3:替代方案(长期推荐)
由于SparkDL已停止维护,推荐使用TensorFlow Hub结合Spark UDF实现图像特征提取功能,无需依赖旧版SparkDL:
import tensorflow as tf import tensorflow_hub as hub from pyspark.sql.functions import udf from pyspark.sql.types import ArrayType, FloatType # 加载预训练的ResNet50特征提取模型 feature_extractor = hub.load("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/5") # 定义UDF用于批量提取图像特征 def get_image_features(image_path): # 读取并预处理图像 img = tf.io.read_file(image_path) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize(img, [224, 224]) img = tf.keras.applications.resnet_v2.preprocess_input(img) # 提取特征并转换为列表格式 features = feature_extractor(tf.expand_dims(img, 0)) return features.numpy().tolist()[0] # 注册UDF feature_udf = udf(get_image_features, ArrayType(FloatType())) # 读取图像文件并生成特征列 image_df = spark.read.format("binaryFile").load("/dbfs/path/to/your/images") result_df = image_df.withColumn("image_features", feature_udf("path")) # 查看结果 result_df.show(5)
内容的提问来源于stack exchange,提问作者callme_fantastique
相关产品推荐
相关产品推荐

