search
HomeTechnology peripheralsAILet's take you through the installation of TensorFlow

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

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

sudo apt update
sudo apt install python3-dev python3-pip python3-venv

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

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

python -c "import TensorFlow

2.1.2 Source code compilation and installation

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

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

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 用户名

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

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]))

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)

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])

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

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

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

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

示例一:assign用来更新值

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

输出结果如下:

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

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

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

输出结果如下:

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

示例三: 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进行输出

2.2.2.3改变变量的形状

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

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

输出结果如下:

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

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

方式二进行自动关闭(使用到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)

安装好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!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Tesla's Robovan Was The Hidden Gem In 2024's Robotaxi TeaserTesla's Robovan Was The Hidden Gem In 2024's Robotaxi TeaserApr 22, 2025 am 11:48 AM

Since 2008, I've championed the shared-ride van—initially dubbed the "robotjitney," later the "vansit"—as the future of urban transportation. I foresee these vehicles as the 21st century's next-generation transit solution, surpas

Sam's Club Bets On AI To Eliminate Receipt Checks And Enhance RetailSam's Club Bets On AI To Eliminate Receipt Checks And Enhance RetailApr 22, 2025 am 11:29 AM

Revolutionizing the Checkout Experience Sam's Club's innovative "Just Go" system builds on its existing AI-powered "Scan & Go" technology, allowing members to scan purchases via the Sam's Club app during their shopping trip.

Nvidia's AI Omniverse Expands At GTC 2025Nvidia's AI Omniverse Expands At GTC 2025Apr 22, 2025 am 11:28 AM

Nvidia's Enhanced Predictability and New Product Lineup at GTC 2025 Nvidia, a key player in AI infrastructure, is focusing on increased predictability for its clients. This involves consistent product delivery, meeting performance expectations, and

Exploring the Capabilities of Google's Gemma 2 ModelsExploring the Capabilities of Google's Gemma 2 ModelsApr 22, 2025 am 11:26 AM

Google's Gemma 2: A Powerful, Efficient Language Model Google's Gemma family of language models, celebrated for efficiency and performance, has expanded with the arrival of Gemma 2. This latest release comprises two models: a 27-billion parameter ver

The Next Wave of GenAI: Perspectives with Dr. Kirk Borne - Analytics VidhyaThe Next Wave of GenAI: Perspectives with Dr. Kirk Borne - Analytics VidhyaApr 22, 2025 am 11:21 AM

This Leading with Data episode features Dr. Kirk Borne, a leading data scientist, astrophysicist, and TEDx speaker. A renowned expert in big data, AI, and machine learning, Dr. Borne offers invaluable insights into the current state and future traje

AI For Runners And Athletes: We're Making Excellent ProgressAI For Runners And Athletes: We're Making Excellent ProgressApr 22, 2025 am 11:12 AM

There were some very insightful perspectives in this speech—background information about engineering that showed us why artificial intelligence is so good at supporting people’s physical exercise. I will outline a core idea from each contributor’s perspective to demonstrate three design aspects that are an important part of our exploration of the application of artificial intelligence in sports. Edge devices and raw personal data This idea about artificial intelligence actually contains two components—one related to where we place large language models and the other is related to the differences between our human language and the language that our vital signs “express” when measured in real time. Alexander Amini knows a lot about running and tennis, but he still

Jamie Engstrom On Technology, Talent And Transformation At CaterpillarJamie Engstrom On Technology, Talent And Transformation At CaterpillarApr 22, 2025 am 11:10 AM

Caterpillar's Chief Information Officer and Senior Vice President of IT, Jamie Engstrom, leads a global team of over 2,200 IT professionals across 28 countries. With 26 years at Caterpillar, including four and a half years in her current role, Engst

New Google Photos Update Makes Any Photo Pop With Ultra HDR QualityNew Google Photos Update Makes Any Photo Pop With Ultra HDR QualityApr 22, 2025 am 11:09 AM

Google Photos' New Ultra HDR Tool: A Quick Guide Enhance your photos with Google Photos' new Ultra HDR tool, transforming standard images into vibrant, high-dynamic-range masterpieces. Ideal for social media, this tool boosts the impact of any photo,

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.