学习神经网络tensorflow常见问题笔记

pip install tensorflow 

警告:
WARNING: You are using pip version 20.2.3; however, version 21.1.2 is available.
You should consider upgrading via the ‘d:\lenovosoftstore\install\python1\python.exe -m pip install --upgrade pip’ command.

easy_install -U pip
pip install tensorflow 完成
pip list 可以查看当前的版本

曹健笔记

from tensorflow.examples.tutorials.mnist import input_data  没有tensorflow.examples的时候,需要去官网下载example
https://github.com/tensorflow/tensorflow/releases/tag/v2.5.0   下面有安装包 (Source code)

 pip uninstall tensorflow-gpu 卸载
 
 pip install tensorflow-gpu==2.0.0 -i https://pypi.tuna.tsinghua.edu.cn/simple  用来下载指定的版本
 
 ModuleNotFoundError: No module named 'tensorflow.examples.tutorials’已解决!
	https://blog.csdn.net/weixin_43977534/article/details/107752562

issue:cannot import name ‘get_config’ 即可解决
在keras前面加上tensorflow
from tensorflow.keras import layers

标注工具:LabelImg

tensorflow2.0版本常见问题:
1、Tensor‘ object has no attribute ‘numpy‘处理方法:
添加如下代码:
tf.enable_eager_execution(
config=None,
device_policy=None,
execution_mode=None
)
https://blog.csdn.net/agoodboy1997/article/details/105231380/

2、TypeError: unsupported operand type(s) for /: ‘int’ and ‘Dimension’, please use // instead
acc = total_correct / total_number
改为: acc = total_correct / /total_number
3、TypeError: float() argument must be a string or a number, not 'Dimension’
total_number += x_test.shape[0]
改为: total_number += x_test.shape[0].value
原因: 也就是说,在keras中利用shape获取维度信息时,应该要使用.value。

4、AttributeError: ‘RefVariable’ object has no attribute '_id’
在导包的地方加入tf.enable_eager_execution()

5、ImportError: cannot import name 'get_config’
在安装包前面加tensorflow.

6、Keras 报错When using data tensors as input to a model, you should specify the steps_per_epoch argument
https://blog.csdn.net/qq_43190189/article/details/114090368

'''
trainImage = tf.reshape(trainImage,(60000,28,28,1))#三维的是1
testImage = tf.reshape(testImage,(10000,28,28,1))
'''
trainImage = np.array(trainImage).reshape(60000,28,28,1)
testImage = np.array(testImage).reshape(10000,28,28,1)
把tf改成np就可以解决问题

需要注意的是,只要在代码中出现了数据的reshape用到了tf,那么数据就变成了tensor data格式,例如

#data_x_train.shape = (256, 28)
tf.reshape(data_x_train, (256, 28, 1), name=tf.float32) 
tf.reshape(data_x_train, (256, 28, 1), name=np.float32) 

上述的两种写法都会使得数据从array或dataFrame或list变成tensor,所以为了避免使用steps_per_epoch(好多时候有问题都不知道怎么改,反正我是不喜欢用这个),可以用numpy的reshape方法来修改数据的维度:

# type(data_x_train) = DataFrame
data_x_train = np.array(data_x_train).reshape(256, 28, 1) 
————————————————
版权声明:本文为CSDN博主「Troye Jcan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43190189/article/details/114090368

另外一种方法,需要打的gpu:https://blog.csdn.net/zhangpeterx/article/details/89290688
7、配置edit configurations问题
https://www.cnblogs.com/wangyue0925/p/11043923.html
https://blog.csdn.net/weixin_41177059/article/details/100884700

注意他们的路径,工作环境和Script环境不一样
选完之后要apply才生效

8、ImportError: cannot import name ‘get_config‘遇到这种问题应该如何解决

# 改变维度 
testImage = tf.reshape(testImage, (10000, 28, 28, 1))
# testImage = np.array(testImage).reshape(10000,28,28,1)

# 结果预测
testImage = tf.cast(testImage, dtype=tf.float32)
# testImage = np.cast(testImage, np.float32)
#没有上面的这一行就会报错,需要转换格式
#报错的意思是你的矩阵是uint8格式,不在范围里,所以我们要做的是把格式转化成报错里说的float32等格式。
#https://blog.csdn.net/St_Louis/article/details/102614001

# 预测前25张图片结果
print(testImage)
# result = network.predict(testImage)[0:25]

**报错**:ValueError: When using data tensors as input to a model, you should specify the `steps` argument.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
解决方案:把tensor转为numpy格式

https://blog.csdn.net/qq_42952590/article/details/118307609
from keras.models import model_
from_yaml import pickle 
from keras import backend as K
**修改为**
``from tensorflow.keras.models import model_
from_yaml import pickle 
from tensorflow.keras import backend as K

9、`# 改变维度
testImage = tf.reshape(testImage, (10000, 28, 28, 1))

testImage = np.array(testImage).reshape(10000,28,28,1)

# 结果预测
testImage = tf.cast(testImage, dtype=tf.float32)

#把tensor转为numpy格式
#https://blog.csdn.net/qq_34840129/article/details/86419020 
sess=tf.Session()
testImage=testImage.eval(session=sess)

#没有上面的这一行就会报错,需要转换格式
#报错的意思是你的矩阵是uint8格式,不在范围里,所以我们要做的是把格式转化成报错里说的float32等格式。
#https://blog.csdn.net/St_Louis/article/details/102614001

# 预测前25张图片结果
print(testImage)
# result = network.predict(testImage)[0:25]`
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
10"Tensor objects are only iterable when eager execution is "
TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.

result = network.predict(testImage)[0:25]
print(result)
pred = tf.argmax(result, axis=1)
# print(pred)
# pred = pred.eval(session=sess)

# # tf.argmax() #0代表列 1代表行 括号内第二个参数 axis=0 时表示按列查找 列表/矩阵 中的最大元素的索引,
# # axis= #1时表示按行查找 列表/矩阵 中最大元素的索引
pred_list = []
for item in pred:
    pred_list.append(item)
print(pred_list)

修改为:
result = network.predict(testImage)[0:25]
print(result)
pred = tf.argmax(result, axis=1)
print(pred)
pred = pred.eval(session=sess):加的这里

# # tf.argmax() #0代表列 1代表行 括号内第二个参数 axis=0 时表示按列查找 列表/矩阵 中的最大元素的索引,
# # axis= #1时表示按行查找 列表/矩阵 中最大元素的索引
pred_list = []
for item in pred:
    pred_list.append(item)
print(pred_list)

10、 x = np.expand_dims(x, axis=0) 经常遇见扩充维度的,为什么?
.要对输入shape扩维变成(None,224,224,3),第一个None是batches,模型并不知道你输入的batches是多少,但是维度必须和ResNet(自己训练的网络的维度)的输入要一致

https://blog.csdn.net/u012193416/article/details/79375832

11、AttributeError: ‘NoneType’ object has no attribute 'get_file’

Traceback (most recent call last):
  File "E:/tensorflow2.0/xception/xeceptionNet.py", line 182, in <module>
    print('Predicted:', decode_predictions(preds))
  File "C:\Users\玄子\AppData\Roaming\Python\Python36\site-packages\keras_applications\imagenet_utils.py", line 225, in decode_predictions
    fpath = keras_utils.get_file(
AttributeError: 'NoneType' object has no attribute 'get_file'

**解决方案:**https://blog.csdn.net/qq_35756383/article/details/103587910

12、对于numpy矩阵来说Y.shape和Y.shape[0]的含义

https://blog.csdn.net/goodgoodstudy___/article/details/107431259?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-1.no_search_link&spm=1001.2101.3001.4242

numpy 数组的 shape 属性返回数组的维度。 如果 Y 有 n 行和 m 列,则 Y.shape 是 (n,m)。 所以 Y.shape[0] 是 n。

13、https://tensorflow.google.cn/install/source#linux
表示tensorflow与cuDNN CUDA对应的版本

nvidia-smi 查看当前的版本(在)
14、查看图像的尺寸
https://tensorflow.google.cn/tutorials/load_data/images(官网)

# img_raw = tf.io.read_file(r"F:\GTSRMcode\GTSRB\dataset\train\00000\210.png")
# mg_tensor = tf.image.decode_image(img_raw)
# print(mg_tensor.shape)

15、The batch_size argument must not be specified for the given input type. Received input:
问题原因:可能数据集制作的时候就使用了.batch(64)做好了,就不用在fit中加入batch_size了?
解决方法:去掉batch_size参数

16、构造的数据集要分好类,要不然rain_datagen.flow_from_directory这个函数会说发现了个图片属于0类。
分类的方法:data\train 的不同类别的照片放不同的文件夹
学习神经网络tensorflow常见问题笔记_第1张图片
学习神经网络tensorflow常见问题笔记_第2张图片
学习神经网络tensorflow常见问题笔记_第3张图片

上面类似的表示方法。
17、WARNING:tensorflow:Can save best model only with val_accuracy available, skipping

history = model.fit(train_generator, epochs=5, callbacks=[cp_callback])
改后:
history = model.fit(train_generator, epochs=5, callbacks=[cp_callback],validation_data=validation_generator,
    validation_steps=50)

警告消失了。

#######################################
18、colab的使用
查看当前分配的gpu:!/opt/bin/nvidia-smi
colab,把数据放到google云盘里面
https://www.jianshu.com/p/a42d69568966(登入谷歌云盘,托文件进去)
挂载的方法(看它的验证码)
挂载代码:
from google.colab import drive drive.mount('/content/gdrive')

http://www.360doc.com/content/21/0214/13/54508727_961997583.shtml
https://blog.csdn.net/zkt286468541/article/details/91536956

19、json和xml文件上面表示的是图片的标注文件
20、File "", line 3, in raise_from tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 2 [[node metrics/acc/Squeeze (defined at D:\LenovoSoftstore\Install\Anaconda\lib\site-packages\tensorflow_core\python\framework\ops.py:1751) ]] [Op:__inference_distributed_function_1726] Function call stack: distributed_function 2021-11-16 23:27:06.493231: W tensorflow/core/kernels/data/generator_dataset_op.cc:102] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized. The process may be terminated. [[{{node PyFunc}}]]
学习神经网络tensorflow常见问题笔记_第4张图片
解决办法:validation_generator = test_datagen.flow_from_directory( directory=validation_dir, target_size=(256, 256), batch_size=1, class_mode='categorical')
改为:validation_generator = test_datagen.flow_from_directory(
directory=validation_dir,
target_size=(256, 256),
batch_size=1,
class_mode=‘binary’)
21、tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[32,64,150,150] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [Op:Conv2DBackpropInput]
显存不够
这是tensorflow 一个经常性错误,错误的原因在于:显卡内存不够。

解决方法就是降低显卡的使用内存,途径有以下几种措施:

1 减少Batch 的大小

2 分析错误的位置,在哪一层出现显卡不够,比如在全连接层出现的,则降低全连接层的维度,把2048改成1042啥的

3 增加pool 层,降低整个网络的维度。

4 修改输入图片的大小

总结以下:想进一切办法降维,降低网络的维度。

22、yolo5接着上次的训练。
AssertionError: runs/train/exp6/weights/last.pt training to 300 epochs is finished, nothing to resume.

你可能感兴趣的:(人工智能,深度学习,人工智能)