泥土巢 - 机器学习之TensorFlow https://www.nituchao.com/category/ml-tf/ zh-CN Wed, 04 Mar 2020 10:56:00 +0800 Wed, 04 Mar 2020 10:56:00 +0800 Ubuntu 18.04安装TensorFlow 1.x GPU版本 https://www.nituchao.com/ml-tf/ubuntu1804-install-tensorflow-1x-gpu.html https://www.nituchao.com/ml-tf/ubuntu1804-install-tensorflow-1x-gpu.html Wed, 04 Mar 2020 10:56:00 +0800 liang Ubuntu 18.04安装TensorFlow 1.x GPU版本

概述

带GPU支持的TensorFlow需要依赖一些驱动和库,主要是NVIDIA显卡驱动和CUDA。另外,推荐使用Anaconda来管理Python环境,并且使用Python 3.6.x版本,以避免不必要的麻烦。

本机环境

  • 操作系统:Ubuntu 18.04.3 LTS
  • Anaconda:conda 5.2
  • Python: Python 3.6.9 :: Anaconda, Inc.
  • Compiler: gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0

必要组件

  • NVIDIA GPU drivers - CUDA 10.0要求410.x及以上。
  • CUDA: TensorFlow支持CUDA 10.0(TensorFlow >= 1.13.0)
  • CUPTI: CUDA性能分析接口组件
  • cuDNN: The NVIDIA CUDA Deeep Neural library(cuDNN),提供了一组经过优化的深度学习操作组件,包括前向卷积,反向卷积,池化,正则化,激活层等。
  • TensorRT: version 5.0,可选,改善某些模型的推理的延迟和吞吐量。
  • TensorFlow: 1.15

note:

Ubuntu系统安装

Ubuntu选择安装界面,在按e键进入编辑界面。
找到"Boot Options ed boot=… initrd=/casper/initrd.lz quiet splash —"
修改红色部分(删去“—”并添加“nomodeset”)如下
“Boot Options ed boot=… initrd=/casper/initrd.lz nomodeset quiet splash”
接着按 '‘F10’'启动系统》

安装NVIDIA显卡驱动

1,使用命令ubuntu-drivers devices 查看当前提供的驱动列表:

== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
modalias : pci:v000010DEd00001C03sv00001043sd000085BFbc03sc00i00
vendor   : NVIDIA Corporation
model    : GP106 [GeForce GTX 1060 6GB]
driver   : nvidia-driver-390 - distro non-free
driver   : nvidia-driver-430 - distro non-free
driver   : nvidia-driver-435 - distro non-free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

== /sys/devices/pci0000:00/0000:00:1c.6/0000:04:00.0 ==
modalias : pci:v000014E4d000043B1sv00001A3Bsd00002123bc02sc80i00
vendor   : Broadcom Limited
model    : BCM4352 802.11ac Wireless Network Adapter
driver   : bcmwl-kernel-source - distro non-free

2,推荐安装最新版本的显卡驱动
使用命令sudo apt install nvidia-driver-435安装显卡驱动,安装成功后重启系统。

3,查看当前显卡信息
使用命令nvidia-smi查看当前先看的驱动版本,内心及处理器信息。

Tue Dec 31 11:18:01 2019       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 435.21       Driver Version: 435.21       CUDA Version: 10.1     |
|-------------------------------|----------------------|----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 106...  Off  | 00000000:01:00.0  On |                  N/A |
| 29%   23C    P8     8W / 120W |    603MiB /  6075MiB |      0%      Default |
+-------------------------------|----------------------|----------------------+
                                                                                
+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1228      G   /usr/lib/xorg/Xorg                            40MiB |
|    0      1274      G   /usr/bin/gnome-shell                          49MiB |
|    0      2081      G   /usr/lib/xorg/Xorg                           300MiB |
|    0      2212      G   /usr/bin/gnome-shell                         210MiB |
+-----------------------------------------------------------------------------+

安装CUDA

在NVIDIA官网的CUDA下载界面,按照操作系统类型选择合适的安装包,我这里选择Ubuntu 18.04 deb[local]。然后使用下面的命令,来安装:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin
sudo mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget http://developer.download.nvidia.com/compute/cuda/10.1/Prod/local_installers/cuda-repo-ubuntu1804-10-1-local-10.1.243-418.87.00_1.0-1_amd64.deb
sudo dpkg -i cuda-repo-ubuntu1804-10-1-local-10.1.243-418.87.00_1.0-1_amd64.deb
sudo apt-key add /var/cuda-repo-10-1-local-10.1.243-418.87.00/7fa2af80.pub
sudo apt-get update
sudo apt-get -y install cuda

安装CUPTI

CUPTI组件包含在CUDA中,无需单独安装。
CUPTI采用懒加载的方式进行初始化,当你第一次调用CUPTI函数时,会触发该初始化操作。
CUPTI提供了包括Activity API,Callback API,Event API,Metric API和Profiler API。

安装cuDNN

现在cuDNN安装包

cuDNN的官网,按照要求勾选一些选项后,进入下载界面,按照操作系统类型选择合适的安装包,我这里选择"Download cuDNN v7.6.5 (November 5th, 2019), for CUDA 10.1"下的运行时库和文档库:

  • cuDNN Runtime Library for Ubuntu18.04 (Deb)
  • cuDNN Developer Library for Ubuntu18.04 (Deb)
  • cuDNN Code Samples and User Guide for Ubuntu18.04 (Deb)

安装cuDNN

载完成后后,使用下面的命令来依次安装

sudo dpkg -i ./libcudnn7_7.6.5.32-1+cuda10.1_amd64.deb
sudo dpkg -i ./libcudnn7-dev_7.6.5.32-1+cuda10.1_amd64.deb
sudo dpkg -i ./libcudnn7-doc_7.6.5.32-1+cuda10.1_amd64.deb

note: cuDNN的runtime, dev, doc三个包要按顺序依次安装。

验证cuDNN

安装完cuDNN的三个组件后,使用如下命令nvidia-smi查看本机NVIDIA驱动程序,如果显然如下错误,则需要重启系统。

Failed to initialize NVML: Driver/library version mismatch

依次执行如下命令,如果结果输出Test passed!,则表示cuDNN安装成功。

cp -r /usr/src/cudnn_samples_v7/ ~/Downloads/cudnn_samples_v7/
cd ~/Downloads/cudnn_samples_v7/mnistCUDNN
make clean && make
./mnistCUDNN

安装TensorFlow

本机在Anaconda环境下安装TensorFlow 2.0.0,Python版本是3.6.9,

$ pip install tensorflow-gpu==2.0.0

note:
1,建议Python版本使用3.6.x,而不是3.7.x。

测试TensorFlow GPU

使用如下代码,如果安装正确,则会输出True

tf.test.is_gpu_available

libcudart.so.10.0解决

如果测试TensorFlow过程中,会出现下面的错误:

2020-01-09 13:44:35.195765: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcudart.so.10.0'; dlerror: libcudart.so.10.0: cannot open shared object file: No such file or directory
2020-01-09 13:44:35.195853: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcublas.so.10.0'; dlerror: libcublas.so.10.0: cannot open shared object file: No such file or directory
2020-01-09 13:44:35.195919: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcufft.so.10.0'; dlerror: libcufft.so.10.0: cannot open shared object file: No such file or directory

原因:TensorFlow2.0现在支持CUDA10.0,还不支持CUDA10.1,而我的Ubuntu上安装的是CUDA10.1(也正确安装了cuDNN)。现在只需要安装一个CUDA10.1就行。可以仿照安装pytorch时就自动安装cudatoolkit 10.1.243,无需再下载CUDA10.0的包,在Ubuntu上重新安装CUDA10.0,而是直接用conda安装cudatoolkit。

conda install cudatoolkit=10.0

Other Problem

安装TensorFlow问题 解决Cannot uninstall 'wrapt'. It is a distutils installed project

]]>
0 https://www.nituchao.com/ml-tf/ubuntu1804-install-tensorflow-1x-gpu.html#comments https://www.nituchao.com/feed/ml-tf/ubuntu1804-install-tensorflow-1x-gpu.html
使用Anaconda管理Python环境 https://www.nituchao.com/ml-tf/anaconda-create-python-evn.html https://www.nituchao.com/ml-tf/anaconda-create-python-evn.html Fri, 13 Jul 2018 09:31:00 +0800 liang 当系统中需要多个版本的python时,使用anaconda或者virtualenv来创建虚拟环境隔离python版本是一个非常好的办法。本文使用anaconda来创建多个隔离环境。

Anaconda Download

官方地址
清华大学镜像
Anaconda3-5.2.0-Linux-x86_64

更改Anaconda的源

推荐使用国内的第三方源来加速Anaconda的包下载速度。Linux/Mac系统可以修改用户目录下的.condarc文件(如果没有可以手动创建):

channels:
  - defaults
show_channel_urls: true
default_channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
custom_channels:
  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud

使用命令conda config --set show_channel_urls yes可以开启下载包时显示源链接。

检查当前系统中anaconda已经创建的环境

可以看到我们系统中目前只有一个base环境。

$conda info --env
# conda environments:
#
base                  *  /home/liang/anaconda3

创建基于python 3.6的开发环境

使用如下命令创建虚拟环境data_analytics_py36,然后anaconda会下载相关的依赖。

$conda create -n data_analytics_py36 python=3.6 anaconda 

查看anaconda虚拟环境列表

$conda info --env
# conda environments:
#
base                  *  /home/liang/anaconda3
micloudml                /home/liang/anaconda3/envs/micloudml

进入虚拟环境data_analytics_py36

$source activate data_analytics_py36

退出虚拟环境data_analytics_py36

$deactivate data_analytics_py36

修改pip源

推荐使用国内第三方源来加速pip,Mac/Linux系统可以修改(如果没有手动创建)~/.pip/pip.conf,添加如下内容:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
]]>
1 https://www.nituchao.com/ml-tf/anaconda-create-python-evn.html#comments https://www.nituchao.com/feed/ml-tf/anaconda-create-python-evn.html
TensorFlow使用线性回归解决特征拟合问题 https://www.nituchao.com/ml-tf/tensorflow-leaner-regression.html https://www.nituchao.com/ml-tf/tensorflow-leaner-regression.html Mon, 21 May 2018 19:17:00 +0800 liang 线性回归(LinearRegression),顾名思义是一种回归模型,拟合一个带有系数 $w = (w_1, ..., w_p)$ 的线性模型,使得数据集实际观测数据和预测数据(估计值)之间的残差平方和最小。其数学表达式为:

$$ \min_{w}||wx - y||_{2}^{2} $$

linear Regression

模型定义

本文旨在使用TensorFlow平台,实现线性回归的过程。

import tensorflow as tf
import numpy as np

# 使用NumPy生成假数据(phony data),总共100个点
x_data = np.float32(np.random.rand(2, 100))
y_data = np.dot([0.100, 0.200], x_data) + 0.3000

# 构造一个线性模型
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y_pre = tf.matmul(W, x_data) + b

# 损失函数:最小化方差
loss = tf.reduce_mean(tf.square(y_pre - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

# 实例化Session,并初始化变量
sess = tf.Session()
sess.run(tf.global_variables_initializer())

# 拟合平面
for step in range(0, 201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(W), sess.run(b))

训练输出

从训练输出可以到,当训练200轮后,得到了稳定的权重向量w和b。
最终的线性拟合曲线为: $y = 0.10000989x_{0} + 0.2000066x_{1} + 0.29999176$

    0 [[ 0.66747683  0.33177963]] [-0.11118987]
    20 [[ 0.2787464   0.28042707]] [ 0.17062303]
    40 [[ 0.15737668  0.23200317]] [ 0.2553007]
    60 [[ 0.11898003  0.21165822]] [ 0.28466448]
    80 [[ 0.10637598  0.20409651]] [ 0.294756]
    100 [[ 0.10215825  0.20141646]] [ 0.29820964]
    120 [[ 0.10073327  0.20048615]] [ 0.29938921]
    140 [[ 0.10024957  0.20016627]] [ 0.29979169]
    160 [[ 0.10008503  0.20005679]] [ 0.29992896]
    180 [[ 0.10002899  0.20001937]] [ 0.29997575]
    200 [[ 0.10000989  0.2000066 ]] [ 0.29999176]
]]>
2 https://www.nituchao.com/ml-tf/tensorflow-leaner-regression.html#comments https://www.nituchao.com/feed/ml-tf/tensorflow-leaner-regression.html
TensorFlow使用神经网络解决异或分类问题 https://www.nituchao.com/ml-tf/tensorflow-cnn-xor.html https://www.nituchao.com/ml-tf/tensorflow-cnn-xor.html Mon, 21 May 2018 19:10:00 +0800 liang 异或(XOR),是一个数学逻辑运算。如果a、b两个值不相同,则异或结果为1。如果a、b两个值相同,异或结果为0。

xor

从上图我们可以看出,与(AND),与非(NOT AND),或(OR)等三种情况,都可以找到不止一条直线将各种情况分类开,但是对于异或(XOR),则找不出一条直线,将其进行分类。本质上,异或是一种线性不可分问题。

本文将使用2层神经网络模型,来解决异或问题。具体代码如下:

import tensorflow as tf

# 定义异或问题的输入和标签
X = [[0, 0], [0, 1], [1, 0], [1, 1]]
Y = [[0], [1], [1], [0]]

x_ = tf.placeholder(tf.float32, shape=[4, 2])
y_ = tf.placeholder(tf.float32, shape=[4, 1])

# 定义中间层列维度
HU = 3

# 输入层到中间层的定义
with tf.name_scope("input") as scope:
    W1 = tf.Variable(tf.random_uniform([2, HU], -1.0, 1.0))
    b1 = tf.Variable(tf.zeros([HU]))
    O = tf.nn.sigmoid(tf.matmul(x_, W1) + b1)
    layer1_sum = tf.summary.scalar("liang", O)

# 中间层到输出层的定义 
with tf.name_scope("output") as scope:
    W2 = tf.Variable(tf.random_uniform([HU, 1], -1.0, 1.0))
    b2 = tf.Variable(tf.zeros([1]))
    y = tf.nn.sigmoid(tf.matmul(O, W2) + b2)
    layer2_sum = tf.summary.scalar("jian", y)

# 损失函数使用:最小二乘法,即最小化均方差
with tf.name_scope("train") as scope:
    cost = tf.reduce_sum(tf.square(y_ - y), reduction_indices=[0])
    train_sum = tf.summary.scalar("cost", cost)
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cost)

# 实例化Session,并初始化变量
sess = tf.Session()
sess.run(tf.global_variables_initializer())


# 设置运行步长
Ecoches = 5000
for i in range(Ecoches):
    sess.run(train_step, feed_dict={x_ : X, y_ : Y})
    
    if i % 500 == 0:
        result = sess.run(cost, feed_dict={x_ : X, y_ : Y})
        print('Epoch ', i)
        print('Cost ', result)

# 计算预测值与实际值之间的准确率
correcct_prediction = abs(y_ - y) < 0.5
cast = tf.cast(correcct_prediction, "float")
accuracy = tf.reduce_mean(cast)

yy, aa = sess.run([y, accuracy], feed_dict={x_:X, y_:Y})
print("Output: ", yy)
print("Accuracy: ", aa)

运行代码后,看到训练过程日志:

Epoch  0
Cost  [ 1.01291001]
Epoch  500
Cost  [ 0.99675679]
Epoch  1000
Cost  [ 0.97751558]
Epoch  1500
Cost  [ 0.85073531]
Epoch  2000
Cost  [ 0.6944164]
Epoch  2500
Cost  [ 0.1805]
Epoch  3000
Cost  [ 0.05683474]
Epoch  3500
Cost  [ 0.03097299]
Epoch  4000
Cost  [ 0.02076247]
Epoch  4500
Cost  [ 0.01544176]
]]>
1 https://www.nituchao.com/ml-tf/tensorflow-cnn-xor.html#comments https://www.nituchao.com/feed/ml-tf/tensorflow-cnn-xor.html
在Jupyter Notebook中使用TensorFlow https://www.nituchao.com/ml-tf/tensorflow-at-jupyter-notebook.html https://www.nituchao.com/ml-tf/tensorflow-at-jupyter-notebook.html Sat, 14 Apr 2018 16:00:00 +0800 liang 环境
System: Ubuntu 18.04
Anaconda: conda 4.4.10
Python: Python 3.6.4 :: Anaconda, Inc.
TensorFlow: tensorflow-1.7.0-cp36-cp36m-linux_x86_64

1,安装Anaconda
从官网下载Anaconda的安装包,执行sh命令安装即可。

2,安装TensorFlow
按照官网的安装指南,通过pip命令安装TensorFlow即可。

3,创建虚拟环境

$ conda create -n tensorflow python=3.6

4,启动虚拟环境

$ source activate tensorflow

5,安装iPython和Jupyter

$ conda install ipython
$ conda install juypter

6,查看Jupyter Kernel路径
查看Jupyter Kernel路径,从结果中可以看到,当前的Jupyter Kernel路径为:/home/liang/.local/share/jupyter/kernels/python3

$ jupyter kernelspec install-self --user
[InstallNativeKernelSpec] Removing existing kernelspec in /home/liang/.local/share/jupyter/kernels/python3
[InstallNativeKernelSpec] Installed kernelspec python3 in /home/liang/.local/share/jupyter/kernels/python3

7,创建TensorFlow Kernel路径
为TensorFlow Kernel命名为tfkernel

$ mkdir -p ~/.ipython/kernels
$ mv /home/liang/.local/share/jupyter/kernels/python3 mv /home/liang/.ipython/kernels/tfkernel

8,重命名新Kernel在Notebook中的名字
使用下面的命令,打开新Kernel的配置文件

$ vim /home/liang/.ipython/kernels/tfkernel/kernel.json

将"display_name"中的默认值Python 3替换为"TF@Python 3",保存,并退出。

9,验证
打开一个新的Jupyter Notebook

$ jupyter notebook

新建一个新的Notebook文件,在菜单栏里依次选择"Kernel" -> "Change kernel" -> "TF@Python 3"。

输入一行import tensorflow as tf并运行,如果没有出现任何错误,表示环境已经生效。

10,后台运行
可以通过screen命令,新建一个Session,在这个Session里运行一个Jupyter Note,然后Detach该Session即可。

]]>
0 https://www.nituchao.com/ml-tf/tensorflow-at-jupyter-notebook.html#comments https://www.nituchao.com/feed/ml-tf/tensorflow-at-jupyter-notebook.html