Home > Technology peripherals > AI > body text

Let's take you through the installation of TensorFlow

王林
Release: 2023-04-12 20:31:01
forward
1849 people have browsed it

1. Basic introduction and understanding

1.1 Introduction

As a comprehensive and flexible open source machine learning platform, we can use TensorFlow to create applications for desktop, mobile, web and cloud Environmental machine learning model, can also be simply said that TensorFlow is an open source machine learning framework. We can use TensorFlow to quickly build neural networks, and at the same time quickly train, evaluate and save the network.

After we install TensorFlow, we can directly import TensorFlow every time we use it.

import TensorFlow as tf

The official website of TensorFlow is as follows:

About TensorFlow |TensorFlow Chinese Official website (google.cn)

Let's take you through the installation of TensorFlow

1.2 Advantages and disadvantages analysis and architecture interpretation

1.2.1 Advantages

● High flexibility: As long as the calculation can be expressed as a calculation flow graph, TF can be used.

● True portability: supports desktops, servers (both CPU and GPU), and embedded devices.

● Multi-language support: Based on Python, it also provides C user interface and Ipython interactive interface.

● Visualization tool: TensorFlow provides a powerful visualization tool, TensorBoard.

● Rich package library support: TFlearn, TF-Slim, Keras, etc.

1.2.2 Disadvantages

● Does not support Windows

## Aside from all the advantages TensorFlow has to offer, its functionality for Windows users is very limited. It is very friendly to Linux users.

● Supports GPU

##TensorFlow only supports NVIDIA GPUs support and Python programming language support for GPU programming.

1.2.3 Interpretation of TensorFlow architecture

Let's take you through the installation of TensorFlow

The first layer: the device communication layer, consisting of the device layer and the network layer, is responsible for Network communications and device management. Device management can realize the heterogeneous characteristics of TF devices. The device layer supports the communication implementation of different devices such as CPU, GPU, and Mobile. Network communication relies on the

gRPC communication protocol to realize data transmission and updates between different devices.

The second layer: Kernel implementation layer, which takes Tensor as the processing object, relies on network communication and device memory allocation, and implements various Tensor operations or calculations, mainly the kernel implementation of machine learning .

The third layer: graph computing layer, composed of distributed master control and data flow executor, including the implementation of local computing flow graph and distributed computing flow graph. The distributed master distributes different workloads on different devices according to load capabilities, and the data flow executor executes the data flow graph based on the best experimental method.

The fourth layer : API interface layer, C API is the interface encapsulation of TF function module, which is implemented in C language. C language was chosen because it is a low-level language, simple, fast, reliable, and can run on any operating system.

The fifth layer: Client layer, Python, C and other programming languages ​​call TF core functions through the API interface layer in the application layer to implement related experiments and applications.

The last layer of TensorFlow contains training and inference libraries implemented in python and C.

If you want to fully understand the basic theory and design ideas of TensorFlow introductory practical operation, you can go to China University MOOC to study "TensorFlow Introductory Practical Course" , quickly get started with the basic applications and practices of TensorFlow.

2. Installation and use

2.1 Installation

Here we take Ubuntu 16.04 or higher (64-bit) as an example

2.1.1 Install using pip

PIP is a package management system used to install and manage software packages written in Python.

First we need to install the python environment, which requires Python 3.6-3.9 and pip 19.0 and higher. If you are not sure whether we have installed it, you can pass the version Check the method to ensure that you can continue.

python3 –version
pip3 --version
Copy after login

If it is not installed, please refer to the following code:

sudo apt update
sudo apt install python3-dev python3-pip python3-venv
Copy after login

Key point: In fact , here I recommend installing anaconda for the installation of python, which can save a lot of things. anaconda contains more than 190 scientific packages and their dependencies such as conda and Python. It can reduce various library problems and version problems.

SecondlyWe need to establish an environment. The recommendation here is to install a virtual environment

Finally we activate the virtual environment environment, and then install the TensorFlow pip software package in the virtual environment

pip install --upgrade TensorFlow
Copy after login

After the installation is completed, you can verify it to ensure that the installation is successful

python -c "import TensorFlow
Copy after login

2.1.2 Source code compilation and installation

git clone --recurse-submodules
https://github.com/TensorFlow/TensorFlow
Copy after login

Installation

Reference https:/ /www.php.cn/link/a03caec56cd82478bf197475b48c05f9

Configure./configureTruthfully answer a series of questions based on your actual situation . After answering, bazel will configure the environment. At this time, the machine needs to be able to access the external network to facilitate obtaining some compilation dependency packages. Some packages may need to be jumped over the wall.

Compile

bazel build -c opt --config=cuda
//TensorFlow/tools/pip_package:build_pip_package
Copy after login

2.1.3 Docker image installation

Docker is an open source application container engine that allows developers They can package their application and dependencies into a portable container and publish it to any popular Linux machine, which can also be virtualized.

When you install and run TensorFlow via Docker, it is completely isolated from previously installed packages on your machine.

Official Image

Officially provides 4 Docker images for use:

Only CPU version, no development environment: gcr.io/TensorFlow/TensorFlow

Only CPU version, no development environment: gcr.io/TensorFlow/TensorFlow:latest- devel

Supports GPU, no development environment: gcr.io/TensorFlow/TensorFlow:latest-gpu

Supports GPU, no development environment: gcr.io/TensorFlow/TensorFlow:latest-devel-gpu

Create Docker user group

Allow normal users Containers can be started without sudo.

usermod -a -G docker 用户名
Copy after login

Start the Docker container

I am using the version that supports GPU, so I chose the fourth one for installation. You can check which version your computer supports and download the corresponding command.

docker run -it 
gcr.io/TensorFlow/TensorFlow
Copy after login

2.2 Use

2.2.1 Placeholder

Syntax: tf.compat.v1.placeholder(dtype,shape=None, name=None)

##Example 1:

w =
tf.constant([1, 1, 2, 2, 3, 3], shape=[2, 3])
h =
tf.constant([7, 7, 9, 9, 11, 11], shape=[3, 2])
#下面语法表示的是两个矩阵相乘
l
= tf.matmul(w, h)

with
tf.Session() as
print(sess.run([a,b,c]))
Copy after login

Example 2:

首先import进行导入
import TensorFlow as tf
w = tf.placeholder(dtype=tf.float32)
h = tf.placeholder(dtype=tf.float32)
sum = tf.add(w,h)
## 填充数据时,使用run()方法的feed_dict参数指定张量对应的值即可,数据格式和字典类似。

with tf.Session() as sess:
# 填充占位符,填充形式类字典
res
= sess.run(sum, feed_dict={w: [5], h: [6]})
print(res)
Copy after login

Specific parameter description:

dtype: The data type of the elements in the tensor that will be input.

shape: Default is None: the shape of the tensor that will be input, it is an optional parameter. If no shape is specified, one can enter a tensor of any shape.

● name: 默认为None:操作的名称,可选参数。

2.2.2变量

Variable()构造函数希望变量有一个初始值,它可以是任何种类或形状的Tensor。变量的类型和形式由其初始值定义。形状和变量一旦被创建就会被固定下来。

在众多的参数中,需要注意的是validate_shape: 默认为True。如果是False,允许变量以未知的形状值初始化。如果是True,初始值的形状必须是已知的,这是默认的。

2.2.2.1创建变量

最常见的创建变量方式是使用Variable()构造函数。

import TensorFlow as tf
v = tf.Variable([1,2,3,4,5,6]) #创建变量v,为一个array
print(v) 
#查看v的shape,不是v的值。
## 结果是: <tf.Variable 'Variable:0' shape=(6,), numpy=array([1,2,3,4,5,6],dtype=int32)>
with tf.Session() as sess:
 
sess.run(v.initializer) ##运行变量的initializer。调用op之前,所有变量都应被显式地初始化过。
sess.run(v) ##查看v的值,结果是:array([1,2,3,4,5,6])
Copy after login

注意: 我们在进行初始化的时候也可以按如下书写

init = tf.global_variables_initializer()#全局变量初始化
with tf.Session() as sess:
sess.run(init)
Copy after login

2.2.2.2分配或修改变量中的元素

我们使用assign()方法来修改这个变量。

示例一:assign用来更新值

w = tf.Variable([3, 4,5,6])
w [1].assign(2)
w
Copy after login

输出结果如下:

<tf.Variable ‘Variable:0’ shape=(4,),
numpy=array([3, 2,5,6], dtype=int32)>
## 我们在此处使用assign将数组中的索引为1的值由4更新为2
Copy after login

示例二 : assign_add()用来添加变量值

# create variable
w = tf.Variable([3, 4,5,6])
# using assign_add() function
w.assign_add([1, 1,1,1])
w
Copy after login

输出结果如下:

<tf.Variable ‘Variable:0’ shape=(4,),
numpy=array([4, 5,6,7], dtype=int32)>
## 我们在此处使用assign_add()将数组中的每一个数值加1进行输出
Copy after login

示例三: assign_sub()用来从变量中减去值

# create variable
w = tf.Variable([3, 4,5,6])
# using assign_add() function
w.assign_sub([1, 1,1,1])
w
<tf.Variable ‘Variable:0’ shape=(4,),
numpy=array([2, 3,4,5], dtype=int32)>
## 我们在此处使用assign_sub()将数组中的每一个数值减1进行输出
Copy after login

2.2.2.3改变变量的形状

tf.reshape()方法用于改变变量的形状。必须传递变量和形状。

import TensorFlow as tf
w= tf.Variable([[3, 5, 6, 7]])
tf.reshape(w, shape=(2, 2))
w
Copy after login

输出结果如下:

<tf.Tensor: shape=(2, 2), ,
numpy=array([[3, 5],[6, 7]], dtype=int32)>
Copy after login

2.2.3 Session会话

TensorFlow中只有让Graph(计算图)上的节点在Session(会话)中执行,才会得到结果。Session的开启涉及真实的运算,因此比较消耗资源。在使用结束后,务必关闭Session。

方式一进行手动关闭:

import TensorFlow as tf
w= tf.constant(8, dtype=tf.int8)
h = tf.constant(6, dtype=tf.int8)
result= w + h
sess = tf.Session()
sess.run(result)#执行运算
sess.close() #手动关闭session
Copy after login

方式二进行自动关闭(使用到with语句):

import TensorFlow as tf
w= tf.constant(8, dtype=tf.int8)
h = tf.constant(6, dtype=tf.int8)
result= w + h
with tf.Session() as sess: #运算结束后session自动关闭
sess.run(res)
Copy after login

安装好TensorFlow后,初步入门机器学习的同学可以到中国大学MOOC上学习《 TensorFlow 入门实操课程 》,快速了解如何使用TensorFlow建立和训练神经网络、用自然语言处理系统教会机器理解、分析和回应人类的言语 、构建和训练模型等基本理论。我推荐对模型部署有需求的同学可以去了解《 TensorFlow 入门课程 - 部署篇 》,高效掌握在多种生产场景下灵活部署模型的技巧。大家也可以在TensorFlow官网(https://www.php.cn/link/e48382353dc6c66379fb8e1ebf48c5e8)上探索更多学习资源,持续精进机器学习知识与技能!

作者介绍

张云波,活跃的IT网红讲师,拥有学员31w+,国内早期开始和发布苹果Swift、安卓Kotlin、微信小程序、区块链技术的讲师之一。主攻前端开发、iOS开发、Android开发、Flutter开发、区块链Dapp开发,有丰富的大公司和海外工作经验。

The above is the detailed content of Let's take you through the installation of TensorFlow. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template