Keras解决ImportError: cannot import name ‘pad_sequences‘ from ‘keras.preprocessing.sequence‘报错

项目场景:

Python使用Keras作为深度学习模型的框架


问题描述

代码中有:

from keras.preprocessing.sequence import pad_sequences
...
...
in_seq, out_seq = seq[:i], seq[i]
in_seq = pad_sequences([in_seq], maxlen=max_length)[0]
...
...
sequence = tokenizer.texts_to_sequences([in_text])[0][-100:]
sequence = pad_sequences([sequence], maxlen=max_length)

出现报错:

ImportError: cannot import name 'pad_sequences' from 'keras.preprocessing.sequence'

原因分析:

from keras.preprocessing.sequence import pad_sequences
这个 import 调用到了"…/site-packages/keras/backend.py"文件中的 from tensorflow.python.eager.context import get_config


解决方案:

from keras.preprocessing.sequence import pad_sequences 改为:

from tensorflow.keras.preprocessing.sequence import pad_sequences

类似的报错还有
from keras.preprocessing.image import array_to_img, img_to_array, load_img ,应改为:

from tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img

参考引用:

TensorFlow使用keras报错ImportError: cannot import name ‘get_config‘ from ‘tensorflow.python.eager.contex

你可能感兴趣的:(keras,tensorflow,python,深度学习,lstm)