【持续更新】运行python代码时遇到的问题及解决方案

【持续更新】运行python代码时遇到的问题及解决方案

写在最前面,网上解决方案太零散,我将遇到的问题进行汇总并在适当的时候分类如安装包版本问题或程序有bug等。
如果学会使用document文档,一切都好说如何使用document
https://www.tensorflow.org/install/source?hl=zh-cn#tested_build_configurations

问题0:TensorFlow环境配置

常见情况

基本大部分TensorFlow问题来源自环境没搭好,请严格执行官方提供的对应版本
TensorFlow官方经过测试的构建配置

例外

在高性能服务器(如A40,A5000)上运行TensorFlow1.x时,会报例如

  • Internal error Blas xGEMV launch failed
  • failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
  • failed to run cuBLAS routine cublasSgemm_v2: CUBLAS_STATUS_EXECUTION_FAILED
  • tensorflow.python.framework.errors_impl.InternalError: Blas GEMM launch failed
  • Segmentation fault (core dumped)
  • Internal: cuDNN launch failure
    等问题,这时排除是适配版本问题,修改安装nvidia-tensorflow,具体可见另一篇博客的TensorFlow安装部分【持续更新】linux系统 常用操作命令-安装tensorflow

问题1:ImportError: DLL load failed: 找不到指定的程序

问题描述及解决方案

一般为安装包版本问题,大部分情况下直接卸载当前版本并安装低版本的模块;
也可按以下顺序逐一检查:
检查模块是否存在>>检查环境变量是否正确**>>检查库的版本兼容性>>检查依赖关系

pip uninstall xxxx
pip install xxxx==0.6.0

问题2:OSError: [WinError 127] 找不到指定的程序

问题描述及解决方案

与问题1一样,卸载高版本库或安装包,安装对应版本
(我当时是导入torchtext报错,后来重新安装低版本后正常运行,详细安装可参考torchtext安装教程

问题3:ERROR: Could not find a version that satisfies the requirement XXX

问题描述

这种是在pip安装程序时出现,可能的问题时网络不稳定或在当前下载源下找不到适配版本,可以通过以下方式尝试解决。

解决方案一:更换下载源

pip install 包名 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

解决方案二:去官网下载

官网PyPI搜索并下载,可以使用官网指定代码,也可以下载whl文件,本地安装。

问题4:AttributeError: module ‘tensorflow’ has no attribute ‘set_random_seed’

问题描述

该问题出现的原因是:安装的tensorflow版本是2.0的,所以使用以前的代码tensorflow中的函数不兼容。

解决方案一:修改代码

import tensorflow as tf

替换为

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

解决方案二:更换适配的低版本 TensorFlow

问题5:AttributeError: module ‘tensorflow.compat.v1’ has no attribute ‘contrib’

问题描述

init = tf.global_variables_initializer()
regularizer = tf.contrib.layers.l2_regularizer(scale = 1e-10)
initializer = tf.contrib.layers.xavier_initializer()
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize
 tf.contrib.layers.batch_norm() #这个函数比较复杂,我没有找到完美的替换2.0函数,建议回退版本 

这种tensorflow版本问题,多半出现在古早的代码使用tensorflow2.0+版本运行;因为tensorflow已经进行多次迭代,修改了许多库函数;
具体可参考官方说明文档在 TF2 工作流中使用 TF1.x 模型
比如TensorFlow 2.x之后把contrib这个库取消了,contrib的内容可以集成到下面三个包中:

解决方案一:修改代码

tf.compat.v1.disable_eager_execution()(如有需要)
init = tf.compat.v1.global_variables_initializer()
regularizer = tf.keras.regularizers.l2(1e-10)
initializer = tf.keras.initializers.glorot_normal()
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate).minimize

解决方案二:更换适配的低版本 TensorFlow

回退tf1.0版本,一般服务器没问题,到性能服务器(A40等)的话,建议参考
【持续更新】linux系统 常用操作命令-安装tensorflow

问题6:GPU数据转到CPU的一个问题:‘XXX‘ object has no attribute ‘cpu‘ or AttributeError: ‘tuple’ object has no attribute ‘to’

问题描述

我们在将GPU的tensor转到CPU时,往往会直接使用tensor.cpu()或者是tensor.to("cpu“),这时明明是tensor,但却不能直接转,原因可能是虽然是tensor,不过tensor可能是list,所以他会优先调用list的内部方法,从而造成这种错误。

解决方案:修改代码

改成如下代码即可顺利运行

targets = torch.tensor(targets, device='cpu')

问题7:AttributeError: module ‘numpy’ has no attribute ‘object’.

问题描述

此问题发生在创建conda环境之后,使用conda install tensorflow-gpu进行安装,安装成功之后在 .py 文件中运行如下代码:

AttributeError: module 'numpy' has no attribute 'object'.
`np.object` was a deprecated alias for the builtin `object`. To avoid this error in existing code, use `object` by itself. Doing this will not modify any behavior and is safe.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
    https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations

解决方案:修改为适配版本

pip install numpy==1.23.4

问题8:AttributeError: module ‘keras.initializers’ has no attribute ‘normal’

问题描述

这种属于高版本配低版本,找不到此属性
初始化权重,使用标准正态分布

return initializers.normal(mean=0.0, stddev=0.01)

解决方案一:更换适配的低版本

解决方案二:修改代码

将原先代码修改为功能相同的高版本方法,初始化权重,使用生成服从正态分布的随机数

return initializers.RandomNormal(mean=0.0, stddev=0.01)

问题9:Non-OK-status: GpuLaunchKernel……Internal: invalid configuration argument

问题描述

这种问题多半是模型本身有问题,当时我出现在使用GPU跑tensorflow-gpu的代码时,属于内部赋值或调用混乱;当然网上有说属于显存爆了,我当时把batch size 设为1,还报错,所以排除;另外一个例子就是多卡训练,batch_size要是使用gpu数量的整数倍,他通过修改batch size解决(在使用Tensorflow 分布式训练出现的Non-OK-status: GpuLaunchKernel问题)。

解决方案:重新检查模型

我当时是检查了自己代码,删除了无用且可能造成错误的代码,如不同py文件重复import tensorflow但没有用它。

问题10:Non-OK-status: Internal: invalid configuration argument Aborted (core dumped)

问题描述

如果你同时使用tf和pytorch,一定要先导入tf,再导入pytorch(花了我好长时间才知道)
与问题9相似,参考方案同
另外附一个更加具体的 Linux遇到Aborted (core dumped),希望对你有帮助 ! ^ _^ !

问题11:ValueError: cannot switch from manual field specification to automatic field numbering

问题描述

format() 函数格式化输出错误,无法从手动字段规范切换到自动字段编号,
错误代码

' Test  lr: {0} \t Weight:{1} =====> Precision:{:.4f} '.format(l_r, layers, m_t_res[0])

解决方案:修改代码

可以同时使用但得注意规范

' Test  lr: {0} \t Weight:{1} =====> Precision:{2:.4f} '.format(l_r, layers, m_t_res[0])

问题12:TypeError: Descriptors cannot not be created directly

问题描述

详细报错如下:

TypeError: Descriptors cannot not be created directly.
If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
 1. Downgrade the protobuf package to 3.20.x or lower.
 2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).

解决方案:重新安装软件包

出现这个问题的主要原因是protobuf版本不匹配。因此,按照错误提示,用pip安装对应版本的protobuf即可,如上述问题中对应的 3.20.1版本。安装命令为:

pip install protobuf==3.20.1

问题13:AttributeError: module ‘tensorflow.compat.v2.internal’ has no attribute ‘dispatch’

问题描述

运行此代码时出现问题

from keras import initializers

解决方案:修改为适配版本

我的tensorflow是2.4.1,将keras修改为2.4.3后问题解决。
在这里插入图片描述
在这里插入图片描述

问题14:ValueError: Variable XXX already exists, disallowed.

问题描述

运行此代码时出现问题

ValueError: Variable conv1/weights already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?

解决方案:添加如下代码

该问题通常在重定义TensorFlow网络模型时出现,可在代码最开始添加 tf.reset_default_graph() ,清除默认图并重置;把他放到还未定义变量或者模型定义前即可

问题15:An unexpected error has occurred. Conda has prepared the above report.

问题描述:

在使用conda搭建虚拟环境时出现

解决方案:关闭VPN

关闭VPN无效,可尝试:
1、删除.condarc文件(这个文件位置一般为C:\User\Administrator.condarc,如果设置了清华/中科大源,里面会保存这些镜像源的地址,删除了这个文件其实就是类似于恢复使用官方源。)
2、清理缓存索引
删除conda中的缓存索引,运行如下命令:

conda clean -i

问题16:OSError: [WinError 1455] 页面文件太小,无法完成操作。

问题描述:

正常跑代码遇到的,这个问题其实就是内存不够

解决方案:

把他看做如何减少模型使用内存或增加计算机内存就好了

(1)修改模型batchsize

(2)修改模型dataloader的num_works(如有)

(3)kill掉其他占用内存多的程序

(4)重启电脑只运行他

(5)增加电脑虚拟内存

具体操作可参考增加虚拟内存

问题17:AttributeError: ‘NoneType’ object has no attribute ‘origin’

问题描述:

安装pytorch geometric时的版本问题

解决方案:卸载并重新安装适配版本

pyg官网
温馨提示:可以先安装pytorch,再使用pip安装pytorch_geometric

问题18:ModuleNotFoundError: No module named ‘torch_sparse‘

问题描述:

pytorch geometri对应的依赖包版本适配问题

解决方案:卸载并重新安装适配版本

根据官网来,pyg官网

问题19:AssertionError: Torch not compiled with CUDA enabled

问题描述:

运行pytorch时出现,其实就是版本不适配

解决方案:卸载并重新安装适配版本

问题20:TypeError: cannot assign ‘torch.cuda.FloatTensor‘ as……

问题描述:

将torch.cuda.FloatTensor类型数据进行赋值时出现

self.running_mean = running_mean_out

解决方案:类型转换

不能直接赋值给Parameter类型,所以我们在此处可以做一下类型转换

self.running_mean = nn.Parameter(running_mean_out,requires_grad=False)

问题21:AttributeError: ‘module’ object has no attribute ‘matmul’

问题描述:

调用Numpy包中方法是出现此问题

解决方案:升级numpy

numpy1.10后才增加了matmul方法,所以在此之前的版本都会报错
使用以下代码升级

pip install --upgrade numpy

问题22:AttributeError: module ‘tensorflow._api.v2.io.gfile’ has no attribute ‘get_filesystem’

问题描述:

此问题是在使用writer.add_embedding时报错

解决方案:

添加如下代码

import tensorflow as tf
import tensorboard as tb
tf.io.gfile = tb.compat.tensorflow_stub.io.gfile

问题23:AttributeError: module ‘tensorflow’ has no attribute ‘variable_scope’

问题描述:

tensorflow2.0与tensorflow1.x冲突问题

解决方案一:修改代码

将tf.variable_scope()修改为tf.compat.v1.variable_scope()

解决方案二:更换适配的低版本

问题24:AttributeError: module ‘tensorflow‘ has no attribute ‘get_variable‘

解决方案:与问题5和问题23雷同

问题25:AttributeError: module ‘tensorflow’ has no attribute ‘truncated_normal’

问题描述:

tensorflow2.0与tensorflow1.x冲突问题

解决方案:

将tf.truncated_normal()修改为tf.random.truncated_normal()

问题26:AttributeError: module ‘tensorflow‘ has no attribute ‘Session‘

解决方案:与问题5和问题23雷同

还报错,如问题27,加

tf.compat.v1.disable_eager_execution()

问题27:RuntimeError: tf.placeholder() is not compatible with eager execution.

解决方案:见问题26

问题28:AttributeError: module ‘tensorflow’ has no attribute ‘global_variables_initializer’

解决方案:见问题5

问题29:AttributeError: module ‘tensorflow._api.v2.train‘ has no attribute ‘GradientDescentOptimize

解决方案:见问题5

警告1:To copy construct from a tensor……

 return torch.tensor(user_graph_index, device=self.device)

出现如下警告:

 UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor)

解决方案:修改调用函数

return torch.as_tensor(user_graph_index, device=self.device)

感谢及参考博文

部分内容参考以下链接,这里表示感谢 Thanks♪(・ω・)ノ
参考博文1 [debug] “ImportError DLL load failed 找不到指定的程序”的解析和解决办法
https://blog.csdn.net/qq_41683065/article/details/99710373
参考博文2 遇到:ImportError: DLL load failed: 找不到指定的模块 错误应该如何解决
https://zhuafan.blog.csdn.net/article/details/132140028
参考博文3 使用torchtext时报错:OSError: [WinError 127] 找不到指定的程序
https://www.codetd.com/article/15430226
参考博文4 torchtext安装教程
https://blog.csdn.net/PolarisRisingWar/article/details/123736491
参考博文5 python使用pip安装包报错的解决办法(ERROR: Could not find a version that satisfies the requirement XXX)
https://blog.csdn.net/qq_43490217/article/details/126639981
参考博文6 解决 AttributeError: module ‘tensorflow.compat.v1‘ has no attribute ‘contrib‘‘问题
https://huaweicloud.csdn.net/63806867dacf622b8df86e7b.html
参考博文7 【TensorFlow】TensorFlow报错及解决方法(持续更新中)
https://blog.csdn.net/qq_36643449/article/details/124542494
参考博文8 yolov5训练模型中遇到的GPU数据转到CPU的一个问题:‘list‘ object has no attribute ‘cpu‘
https://blog.csdn.net/HeiSeXingYe/article/details/120621052
参考博文9 AttributeError: module ‘numpy’ has no attribute ‘object’.解决方法
https://www.jianshu.com/p/66ce2eeb50d3
参考博文10 在使用Tensorflow 分布式训练出现的Non-OK-status: GpuLaunchKernel问题
https://blog.csdn.net/handsofgod/article/details/124668975
参考博文11 如何使用document
https://blog.csdn.net/qq_41413211/article/details/127162512
参考博文12 Linux遇到Aborted (core dumped)
https://blog.csdn.net/qq_35091353/article/details/112101738
参考博文13 学习字符串format()函数时,报错:ValueError: cannot switch from manual field specification to automatic field numbering
https://www.cnblogs.com/00log/p/13236156.html
参考博文14 Descriptors cannot not be created directly
https://blog.csdn.net/suiyingy/article/details/125218783
参考博文15 【解决错误】AttributeError: module ‘tensorflow.compat.v2.internal’ has no attribute ‘dispatch’
https://www.cnblogs.com/wwj321/p/16832760.html
参考博文16 如何使用document
https://blog.csdn.net/qq_32925031/article/details/106820855
参考博文17 创造虚拟环境报错An unexpected error has occurred. Conda has prepared the above report.解决方案
https://blog.csdn.net/qq_49641239/article/details/122127213
参考博文18 YOLOV7:OSError: [WinError 1455] 页面文件太小,无法完成操作的 最终解决方案
https://blog.csdn.net/xty123abc/article/details/125864462
参考博文19 UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone…的解决方案
https://blog.csdn.net/weixin_61745097/article/details/129858870
参考博文20 解决自定义batch_norm训练时报错:TypeError: cannot assign ‘torch.cuda.FloatTensor‘ as parameter ‘running_mean‘
https://blog.csdn.net/TiAmo_forever/article/details/131788528
参考博文21 AttributeError: module ‘tensorflow._api.v2.io.gfile’ has no attribute ‘get_filesystem’
https://github.com/pytorch/pytorch/issues/47139
参考博文22 Non-OK-status: Internal: invalid configuration argument Aborted (core dumped)
https://github.com/keras-team/keras/issues/13093
参考博文23 成功解决AttributeError: module ‘tensorflow‘ has no attribute ‘get_variable‘
https://blog.csdn.net/qq_41185868/article/details/103827393
参考博文24 如何使用document
https://stackoverflow.com/questions/58341433/
参考博文25 tf.layers.batch_normalization 介绍
https://www.cnblogs.com/fclbky/p/12636842.html
参考博文26 tensorflow使用Session模块时报错
https://blog.csdn.net/UCAS2019/article/details/120010881
参考博文27 AttributeError: module ‘tensorflow._api.v2.train‘ has no attribute ‘GradientDescentOptimize
https://blog.csdn.net/zkw_1998/article/details/120830121

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值