Tensorflow深度学习环境搭建

提示:超详细的安装方法

文章目录

  • 前言
  • 一、所需硬件
  • 二、使用步骤
    • 1.安装Anoconda
    • 2.创建tf_gpu环境
    • 3配置 Anaconda 镜像源
    • 4配置虚拟环境tf_gpu
    • 6安装PyCharm
    • 7安装Git
    • 8 安装 TensorFlow Object Decetion API 框架
    • 1)下载 TensorFlow Object Decetion API
    • 2)安装依赖的python包
    • 3)配置环境变量
    • 9安装 COCO API
    • 1)下载 COCO API
    • 2)安装demo运行所需环境
    • 10编译proto文件
    • 11测试安装
    • 1) 下载 ssd_inception_v2_coco 模型
    • 2) 创建 object_detection_example_1.py 文件
    • 3)注释掉visualization_utils.py 中某一行
    • 4)运行 object_detection_example_1.py
    • 12安装LabelImg
  • 总结


前言

本人初次学习,如有错误,还请赐教。


一、所需硬件

打开控制面板->硬件和声音->设备和打印机->设备管理器->显示适配器->显卡
Tensorflow深度学习环境搭建_第1张图片
Tensorflow深度学习环境搭建_第2张图片
我的MX150相当于GT 1030、台式机桌面的GTX650Ti、GTX460/GTX560SE这个显卡级别,性能介于GT740和GTX750显卡之间
看这张显卡天梯图就直观明了了
Tensorflow深度学习环境搭建_第3张图片
看其对应的计算能力,做深度学习,要求计算能力要>=3.5
https://developer.nvidia.com/cuda-gpus#compute
Tensorflow深度学习环境搭建_第4张图片

二、使用步骤

1.安装Anoconda

官网
https://www.anaconda.com/products/distribution#
Tensorflow深度学习环境搭建_第5张图片

2.创建tf_gpu环境

tf:tensorflow
gpu:图形处理器
1)在右边开始那点开,打开 Anaconda Navigator -> Environments -> Create
Tensorflow深度学习环境搭建_第6张图片
Tensorflow深度学习环境搭建_第7张图片
2)创建名为tf_gpu,选择python为3.6的环境。点击create,等待一会。
Tensorflow深度学习环境搭建_第8张图片
创建完毕
Tensorflow深度学习环境搭建_第9张图片
3)点击tf_gpu三角按钮,选择Open Terminal
Tensorflow深度学习环境搭建_第10张图片
控制台打开了,之后就在控制台中操作,这里就是tf_gpu的环境
Tensorflow深度学习环境搭建_第11张图片

3配置 Anaconda 镜像源

我们直接下载要访问国外的服务器,设置成清华镜像源,下载快点。
复制下面代码,粘贴到tf_gpu控制台中

conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes

Tensorflow深度学习环境搭建_第12张图片
Tensorflow深度学习环境搭建_第13张图片

4配置虚拟环境tf_gpu

开始安装tensorflow_gpu库,在控制台上输入下面命令

conda install tensorflow-gpu=1.13

中间输入y回车
需要等待一段时间

代码如下(示例):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

6安装PyCharm

官网下载,安装社区版是完全免费的
https://www.jetbrains.com/pycharm/
Tensorflow深度学习环境搭建_第14张图片
选择安装位置
Tensorflow深度学习环境搭建_第15张图片
勾选桌面快捷方式
Tensorflow深度学习环境搭建_第16张图片
Tensorflow深度学习环境搭建_第17张图片

打开PyCharm,可以配置界面显示风格
Tensorflow深度学习环境搭建_第18张图片

7安装Git

方便去克隆别人的开源项目
可以参考这篇
https://blog.csdn.net/qq_44985985/article/details/112095475

8 安装 TensorFlow Object Decetion API 框架

TensorFlow Object Decetion API 是一个在 TensorFlow 基础上开发出来的用于图像检测并定位的软件框架。

1)下载 TensorFlow Object Decetion API

需要使用git
先创建一个tf_train文件夹,在里面创建addons 和 workspaces两个文件夹。
在空白处右键Git Bash Here
Tensorflow深度学习环境搭建_第19张图片
在Git 中输入
先设置成镜像网站下载,使用hub.fastgit.xyz镜像

git config --global url."https://hub.fastgit.xyz/".insteadOf https://github.com/

再输入

git clone -b r1.13.0 https://github.com/tensorflow/models.git

回车

2)安装依赖的python包

打开 Anaconda Navigator -> Environments -> tf_gpu->Terminal
Tensorflow深度学习环境搭建_第20张图片
输入命令,设置pip镜像源,使用国内清华镜像源,提高速度

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

在这里插入图片描述

3)配置环境变量

win+r输入control
Tensorflow深度学习环境搭建_第21张图片
进入控制面板,搜索”环境变量“
编辑系统环境变量
新建环境变量PYTHONPATH
变量值为之前下载的 TensorFlow Object Decetion API 的路径
例如:
C:\develop\tf_train\models\research
C:\develop\tf_train\models\research\slim
C:\develop\tf_train\models\research\object_detection
三个路径用逗号隔开
Tensorflow深度学习环境搭建_第22张图片

9安装 COCO API

1)下载 COCO API

使用 COCO API 来作为 TensorFlow Object Detection API 的评估指标,用来评估我们模型的表现能力。
进入之前新建的addons文件夹中,
Tensorflow深度学习环境搭建_第23张图片
在空白处右击Git Bash Here
输入git clone https://github.com/philferriere/cocoapi.git
Tensorflow深度学习环境搭建_第24张图片

2)安装demo运行所需环境

安装 COCO API 安装 COCO API 要依赖 Visual C++ Build Tools 2015。如果电脑上已经安装了C++相关开发软件(我的电脑上安装了Visual Studio 2022),可以不用再安装了,如果没有安装推荐安装 Visual C++ Build Tools 2015。如果不安装的话直接进行下一步就会出现 unable to find vcvarsall.bat 错误。
下载地址:http://go.microsoft.com/fwlink/?LinkId=691126。
安装完成后,打开打开 Anaconda Navigator -> Environments-> tf_gpu 的 terminal,进入 cocoapi\PythonAPI 目录下:cd C:\develop\tf_train\addons\cocoapi\PythonAPI(根据自己实际情况修改),
Tensorflow深度学习环境搭建_第25张图片

然后运行安装命令:python setup.py install

中间遇到错误

 File "setup.py", line 2, in 
    from Cython.Build import cythonize
ModuleNotFoundError: No module named 'Cython'

安装
Cython

pip install Cython

如果没有遇到错误可以忽略。

(tf_gpu) C:\develop\tf_train\addons\cocoapi\PythonAPI>python setup.py install
Compiling pycocotools/_mask.pyx because it changed.
[1/1] Cythonizing pycocotools/_mask.pyx
C:\develop\anaconda3\envs\tf_gpu\lib\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: C:\develop\tf_train\addons\cocoapi\PythonAPI\pycocotools\_mask.pyx
  tree = Parsing.p_module(s, pxd, full_module_name)
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.6
creating build\lib.win-amd64-3.6\pycocotools
copying pycocotools\coco.py -> build\lib.win-amd64-3.6\pycocotools
copying pycocotools\cocoeval.py -> build\lib.win-amd64-3.6\pycocotools
copying pycocotools\mask.py -> build\lib.win-amd64-3.6\pycocotools
copying pycocotools\__init__.py -> build\lib.win-amd64-3.6\pycocotools
running build_ext
building 'pycocotools._mask' extension
creating build\temp.win-amd64-3.6
creating build\temp.win-amd64-3.6\Release
creating build\temp.win-amd64-3.6\Release\pycocotools
creating build\temp.win-amd64-3.6\common
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -IC:\develop\anaconda3\envs\tf_gpu\lib\site-packages\numpy\core\include -I../common -IC:\develop\anaconda3\envs\tf_gpu\include -IC:\develop\anaconda3\envs\tf_gpu\include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\cppwinrt" /Tcpycocotools/_mask.c /Fobuild\temp.win-amd64-3.6\Release\pycocotools/_mask.obj
_mask.c
C:\develop\anaconda3\envs\tf_gpu\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(14) : Warning Msg: Using deprecated NumPy API, disable it with #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
pycocotools/_mask.c(3381): warning C4244: “=”: 从“Py_ssize_t”转换到“siz”,可能丢失数据
pycocotools/_mask.c(3791): warning C4244: “函数”: 从“npy_intp”转换到“siz”,可能丢失数据
pycocotools/_mask.c(3791): warning C4244: “函数”: 从“npy_intp”转换到“siz”,可能丢失数据
pycocotools/_mask.c(3791): warning C4244: “函数”: 从“npy_intp”转换到“siz”,可能丢失数据
pycocotools/_mask.c(6798): warning C4244: “=”: 从“npy_intp”转换到“siz”,可能丢失数据
pycocotools/_mask.c(7556): warning C4244: “=”: 从“Py_ssize_t”转换到“siz”,可能丢失数据
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -IC:\develop\anaconda3\envs\tf_gpu\lib\site-packages\numpy\core\include -I../common -IC:\develop\anaconda3\envs\tf_gpu\include -IC:\develop\anaconda3\envs\tf_gpu\include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\cppwinrt" /Tc../common/maskApi.c /Fobuild\temp.win-amd64-3.6\Release\../common/maskApi.obj
maskApi.c
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /nodefaultlib:libucrt.lib ucrt.lib /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\develop\anaconda3\envs\tf_gpu\libs /LIBPATH:C:\develop\anaconda3\envs\tf_gpu\PCbuild\amd64 "/LIBPATH:C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\\lib\10.0.19041.0\\um\x64" /EXPORT:PyInit__mask build\temp.win-amd64-3.6\Release\pycocotools/_mask.obj build\temp.win-amd64-3.6\Release\../common/maskApi.obj /OUT:build\lib.win-amd64-3.6\pycocotools\_mask.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Release\pycocotools\_mask.cp36-win_amd64.lib
  正在创建库 build\temp.win-amd64-3.6\Release\pycocotools\_mask.cp36-win_amd64.lib 和对象 build\temp.win-amd64-3.6\Release\pycocotools\_mask.cp36-win_amd64.exp
正在生成代码
已完成代码的生成
running install_lib
creating C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools
copying build\lib.win-amd64-3.6\pycocotools\coco.py -> C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools
copying build\lib.win-amd64-3.6\pycocotools\cocoeval.py -> C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools
copying build\lib.win-amd64-3.6\pycocotools\mask.py -> C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools
copying build\lib.win-amd64-3.6\pycocotools\_mask.cp36-win_amd64.pyd -> C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools
copying build\lib.win-amd64-3.6\pycocotools\__init__.py -> C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools
byte-compiling C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools\coco.py to coco.cpython-36.pyc
byte-compiling C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools\cocoeval.py to cocoeval.cpython-36.pyc
byte-compiling C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools\mask.py to mask.cpython-36.pyc
byte-compiling C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools\__init__.py to __init__.cpython-36.pyc
running install_egg_info
Writing C:\develop\anaconda3\envs\tf_gpu\Lib\site-packages\pycocotools-2.0-py3.6.egg-info

完成

10编译proto文件

TensorFlow Object Detection API 框架使用 protobuf 工具来配置模型和训练参数,我们在安装 tensorflow-gpu 的时候已经附带安装好了。但是没有经过编译,该工具无法使用,所以接下来的操作就是对 proto 文件进行编译。
打开 Anaconda Navigator -> Environments -> tf_gpu->Terminal
输入命令,切换到C:\develop\tf_train\models\research(根据自己的情况切换)文件夹下

C:\develop\tf_train\models\research

之后输入下面命令

for /f %i in ('dir /b object_detection\protos\*.proto') do protoc object_detection\protos\%i --python_out=.

11测试安装

1) 下载 ssd_inception_v2_coco 模型

在浏览器上输入网址,找到
COCO-trained models->ssd_inception_v2_coco,
下载得到的是压缩包,解压到C:\develop\tf_train\models\research\object_detection文件夹中

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf1_detection_zoo.md

Tensorflow深度学习环境搭建_第26张图片

2) 创建 object_detection_example_1.py 文件

在C:\develop\tf_train\models\research\object_detection文件中
右键创建文档,文档名修改位object_detection_example_1.py
将下面代码粘贴到该文件中

# object_detection_example_1.py演示一个完整的推理(Inference)过程

# -----------------------------------------------------------
# 第一步,导入相关的软件包
# -----------------------------------------------------------
import numpy as np 
import os
import tensorflow as tf 
import matplotlib.pyplot as plt 
from PIL import Image 
from utils import label_map_util
from utils import visualization_utils as vis_util 
from utils import ops as utils_ops

# 检查tensorflow 版本,须≥1.12.0
from pkg_resources import parse_version
if parse_version(tf.__version__) < parse_version('1.12.0'):
    raise ImportError("parse_version:Please upgrade your TensorFlow to V1.12.* or higher")
print("The version of installed TensorFlow is {0:s}".format(tf.__version__))

# GPU 按需分配
config = tf.compat.v1.ConfigProto(allow_soft_placement=True)
config.gpu_options.per_process_gpu_memory_fraction = 0.3
tf.compat.v1.keras.backend.set_session(tf.compat.v1.Session(config=config))

# -----------------------------------------------------------
# 第二步,导入模型ssd_inception_v2_coco_2018_01_28到内存
# ssd_inception_v2_coco_2018_01_28文件夹应与本程序放在models\research\object_detection文件夹下
# -----------------------------------------------------------
MODEL_NAME = 'ssd_inception_v2_coco_2018_01_28'
PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

# -----------------------------------------------------------
# 第三步,导入标签映射文件(Label map),这样假如神经网络输出'5',我
# 们就知道对应的是'airplane'
# -----------------------------------------------------------
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

# -----------------------------------------------------------
# 第四步,执行推理(Inference),检测图片中的对象
# -----------------------------------------------------------

# ## 导入图像数据到numpy array 子程序
def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size 
    return np.array(image.getdata()).reshape((im_height,im_width,3)).astype(np.uint8)

# ## 从单张图片中检测对象子程序
# ## 图片名称:image1.jpg, image2.jpg,存放在
# ## models\research\object_detection\test_images文件夹下
PATH_TO_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [os.path.join(PATH_TO_IMAGES_DIR, 'image{0:d}.jpg'.format(i)) for i in range(1,3)]

# 显示图像的尺寸,单位inches
IMAGE_SIZE = (12, 8)

def run_inference_for_single_image(image, graph):
    with graph.as_default():
        with tf.Session() as sess:
            ops = tf.get_default_graph().get_operations()
            all_tensor_names = {output.name for op in ops for output in op.outputs}
            tensor_dict = {}
            for key in ['num_detections', 'detection_boxes', 'detection_scores',
                'detection_classes', 'detection_masks']:
                tensor_name = key + ':0'
                if tensor_name in all_tensor_names:
                    tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)
            if 'detection_masks' in tensor_dict:
                detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
                detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
                real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
                detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
                detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
                detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                    detection_masks, detection_boxes, image.shape[1], image.shape[2])
                detection_masks_reframed = tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)
                tensor_dict['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)
            image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

            # 运行推理(Inference)
            output_dict = sess.run(tensor_dict,feed_dict={image_tensor: image})

            output_dict['num_detections'] = int(output_dict['num_detections'][0])
            output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.int64)
            output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
            output_dict['detection_scores'] = output_dict['detection_scores'][0]
            if 'detection_masks' in output_dict:
                output_dict['detection_masks'] = output_dict['detection_masks'][0]
    return output_dict

for image_path in TEST_IMAGE_PATHS:
    image = Image.open(image_path)
    image_np = load_image_into_numpy_array(image)
    # 扩展维度,因为模型要求图像的形状为:[1, None, None, 3]
    image_np_expanded = np.expand_dims(image_np, axis=0)
    # 运行检测程序.
    output_dict = run_inference_for_single_image(image_np_expanded, detection_graph)
    # 可视化检测结果.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        output_dict['detection_boxes'],
        output_dict['detection_classes'],
        output_dict['detection_scores'],
        category_index,
        instance_masks=output_dict.get('detection_masks'),
        use_normalized_coordinates=True,
        line_thickness=8)
    plt.figure(figsize=IMAGE_SIZE)
    plt.imshow(image_np)
plt.show()


保存并退出

3)注释掉visualization_utils.py 中某一行

打开 C:\develop\tf_train\models\research\object_detection\utils
找到这一行,
import matplotlib; matplotlib.use('Agg') # pylint: disable=multiple-statements
大约在二十几行,每个人的不一样,我的在27行,推荐用Notepad++打开,在前面加上#

保存并退出

4)运行 object_detection_example_1.py

打开 Anaconda Navigator -> Environments -> tf_gpu->Terminal
,输入命令(注意这里要修改的成自己的目录,我的是在C:\develop\tf_train\models\research\object_detection文件夹下)

cd C:\develop\tf_train\models\research\object_detection

进入到object_detection文件夹下
再输入命令

python object_detection_example_1.py

运行程序
中间出了个错误
File “object_detection_example_1.py”, line 9, in
import matplotlib.pyplot as plt
ModuleNotFoundError: No module named ‘matplotlib’
输入命令
pip install matplotlib

以上所报错最后才发现原因,配置环境变量那块,估计是没有点击确定。请读者每一步都要细心啊。
成功运行会出来下面两幅图

12安装LabelImg

LabelImg 是一个图像标注工具,其标注结果会以 PASCAL VOC 格式存成 XML 文件。
下载网址:https://github.com/tzutalin/labelImg
下载到C:\develop\tf_train\addons文件夹中,以我的为例
Tensorflow深度学习环境搭建_第27张图片
Tensorflow深度学习环境搭建_第28张图片
下载完后,解压,LabelImg软件是一个绿色软件,解压后即可使用。
Tensorflow深度学习环境搭建_第29张图片
进入windows_v1.8.1文件夹中,运行exe程序
Tensorflow深度学习环境搭建_第30张图片
打开一个存放图片的文件夹,可以对图片进行标记


总结

以上就是我学习tensorflow环境安装的过程,包括其中遇到的问题,都有标注出来,读者一定要仔细,一步步来,估计要耗费大半天时间,我安装的时候遇到问题较多,零零散散弄了两天才完成。
参考文档
https://www.cnblogs.com/hillsea/p/12969693.html
https://blog.csdn.net/lemon4869/article/details/106818808

你可能感兴趣的:(点滴,python)