Tensorflow中concat后对tensor执行roll操作致Jupyter Notebook崩溃求助
问题修复方案
根因分析
你提供的代码逻辑本身没有语法错误,Jupyter崩溃核心是TensorFlow执行模式和环境版本不匹配导致:
- 若使用TensorFlow 1.x版本:默认是图执行模式,所有运算OP需要在会话中执行才能得到结果,直接运行
tf.roll(z,1,axis=0)只会生成静态图节点,低版本TF在Jupyter环境下直接输出该节点时容易触发内核崩溃。 - 若使用TensorFlow 2.x版本:默认开启Eager即时执行,该代码可以正常输出
tf.Tensor([0 1 2 0], shape=(4,), dtype=int32),崩溃是环境依赖冲突导致,通常是TensorFlow和numpy、Jupyter内核版本不匹配。
对应修复方法
TensorFlow 1.x环境修复
两种可选方案:
- 开头开启Eager执行(兼容TF2.x写法)
import tensorflow as tf # 开启即时执行,放在所有TF操作之前 tf.enable_eager_execution() x = tf.convert_to_tensor([1,2],dtype="int32") y = tf.zeros(shape=(2),dtype="int32") z = tf.concat([x,y],axis=0) print(tf.roll(z,1,axis=0))
- 用会话包裹运算逻辑
import tensorflow as tf x = tf.convert_to_tensor([1,2],dtype="int32") y = tf.zeros(shape=(2),dtype="int32") z = tf.concat([x,y],axis=0) roll_res = tf.roll(z,1,axis=0) with tf.Session() as sess: print(sess.run(roll_res))
TensorFlow 2.x环境修复
按顺序排查:
- 确认numpy版本和TF版本适配:TF2.4及以上版本要求numpy<=1.19.5,TF2.6及以上版本要求numpy>=1.19.2
- 卸载现有TensorFlow后重新安装稳定适配版本:
pip install tensorflow==2.8.0 --upgrade - 重启Jupyter内核后重新运行代码
内容的提问来源于stack exchange,提问作者rdpdo
相关产品推荐
相关产品推荐

