Python TensorFlow教程

时间:2020-02-23 14:44:05  来源:igfitidea点击:

TensorFlow是由Google Brain团队开发的,供Google内部使用,但是该系统具有足够的通用性,可以应用于各种领域。
2014年11月9日,他们决定将其开源,并根据Apache 2.0开源许可发布。
今天,我们将研究TensorFlow基础知识,然后介绍一些Python TensorFlow示例程序。

TensorFlow

TensorFlow是用于数据流编程的库。
这是一个符号数学库,还用于神经网络等机器学习的应用。

TensorFlow使用各种优化技术来提高计算效率。
在涉及多台机器的计算并涉及庞大的数据集时,TensorFlow具有很高的可扩展性。
这些特性共同使TensorFlow成为机器学习的理想框架。

TensorFlow术语

在本文中,我们将学习更多关于TensorFlow的信息,并通过一些示例来了解如何使用TensorFlow可视化,调整和调试使用它创建的库,但是在使用TensorFlow之前,我们必须知道什么是Tensor和Tensor处理单位。

张量Tensor

张量是TensorFlow中数据的中心单元。
它由存储为多维数组形状的原始值组成。
张量具有的维数称为其秩。

等级0张量只是一个标量。
为了简单起见,我们可以说张量是数组的一个奇特的名称,现在我们将维数称为等级。
让我们看一下张量是什么样的:

1级张量:

[1,2,3,4]

等级2张量:

[[1,2,3,4,],[5,6,7,8]]

张量处理单元(TPU)

TPU是一种可编程的AI加速器,旨在提供高吞吐量的低精度算术运算。
它旨在利用或者运行模型,而不是训练模型。
正如Google声明的那样,他们已经在数据中心内运行TPU超过一年,发现它们为机器学习提供了每瓦更好的优化性能一个数量级。

第二代TPU提供高达180 teraflops的性能,当组织为64个TPU的集群时,可提供高达11.5 petaflops。

TensorFlow入门

我们将从安装Tensorflow开始。

安装TensorFlow

我们将使用TensorFlow Python API,它将与Python 2.7和Python 3.3及更高版本一起使用。

仅适用于Linux:GPU版本需要CUDA 7.0。
+和cuDNN c2 +。

一旦满足这些要求,就可以开始安装。
对于安装,我们可以使用conda或者pip,以您更喜欢的方式使用。

pip安装是标准安装,使用pip只需在终端中运行以下命令(sudo是可选的):

$pip install tensorflow

或者您可以使用以下命令使用conda进行安装:

$conda create --name TensorflowEnv biopython
$source activate TensorFlowEnv
$conda install tensorflow

我们将在第一个命令中安装biopython,以使事情变得更容易,因为它包含一些我们可能需要的软件包。

使用TensorFlow

要在脚本的任何位置使用TensorFlow,只需使用以下import语句将其导入。

import tensorflow

TensorFlow简单表达式

在实际使用简单元素之前,让我们研究一下简单元素以及它们在TensorFlow中的外观。

TensorFlow常数

如果在训练模型中需要常量,则可以使用常量对象。
在TensorFlow中,使用函数constant创建常量。

该函数的签名是:

constant(value, dtype=None, shape=None, name='Const', verify_shape=False)

在此,形状和名称是可选参数。
让我们尝试使用签名创建一个对象:

myConstant = tf.constant(4.5, name="x", dtype=tf.float32)

TensorFlow变量

TensorFlow变量是任何框架的重要组成部分,因为没有变量就不可能编程,它们用于保存和更新值。

在TensorFlow中,当我们训练模型时变量非常有用。
作为常量,我们必须调用构造函数来初始化变量,初始值可以作为参数传递。
创建变量很容易,可以按照以下步骤进行:

myVariable = tf.Variable(tf.zeros([1]), name="myVariable")

如果我们只想将变量用于计算而又不应该对其进行训练,则可以使用如下可训练标志:

k = tf.Variable(tf.add(a, b), trainable=False)

通过调用构造函数,可以轻松将变量添加到计算图。

TensorFlow会话

会话封装了TensorFlow运行时的控件和状态。
会话类接受图参数。
如果我们不向会话传递任何参数,它将使用在当前会话中创建的默认图形。

让我们看一下实际的会话,以更好地了解它:

# Import tensorflow
import tensorflow as tf

# Initialize some constants to be used in session
x = tf.constant(-2.0, name="x", dtype=tf.float32)
a = tf.constant(5.0, name="a", dtype=tf.float32)
b = tf.constant(13.0, name="b", dtype=tf.float32)

# Declare a Variable
y = tf.Variable(tf.add(tf.multiply(a, x), b))

# Assign variable initializer to init
init = tf.global_variables_initializer()

# Start the session
with tf.Session() as session:
  session.run(init)
  print(session.run(y))

让我们通过在终端中运行以上代码来开始会话:

代码显示3.0,该值应为计算后的y值。
另外,请忽略输出前的警告。
由于多个Python版本和其他因素,您可能也会得到它。

定义计算图

计算图是TensorFlow中的内置过程,我们无需显式创建Graph对象的实例。

在TensorFlow中,可以使用简单的代码行创建Graph对象,例如:

c = tf.add(a, b)

这将创建一个将两个数字相加的运算节点。

TensorFlow占位符

如果要将数据注入到计算图中,则必须使用一种称为占位符的机制。
占位符绑定在某些表达式内。
典型的占位符如下所示:

placeholder(dtype, shape=None, name=None)

占位符使我们不必预先提供操作和计算图的数据,并且可以在运行时从外部源添加数据。

让我们看一个例子。
我们将尝试以TensorFlow方式将两个整数相乘,我们将在此处使用占位符:

import tensorflow as tf
# Declare placeholders, Notice we didn't pass any values here
x = tf.placeholder(tf.float32, name="x")
y = tf.placeholder(tf.float32, name="y")
z = tf.multiply(x, y, name="z")
# Start the session to see the result, and pass values from the feed
with tf.Session() as session:
  print(session.run(z, feed_dict={x: 2.6, y: 2.0}))

让我们运行程序,看看会得到什么:

TensorFlow数学

我们已经简要介绍了张量,在这里我们将看到如何将numpy数组转换为张量。
对于转换,我们必须使用内置的函数" convert_to_tensor"。
该函数接受Tensor对象,Numpy数组,Python列表和Python标量。
让我们尝试将二维数组转换为张量。

import tensorflow as tf
import numpy as np

# create several numpy arrays
tensor_2d = np.array(np.random.rand(4, 4), dtype='float32')
tensor_2d_1 = np.array(np.random.rand(4, 4), dtype='float32')
tensor_2d_2 = np.array(np.random.rand(4, 4), dtype='float32')

# convert to tensor
m1 = tf.convert_to_tensor(tensor_2d)
m2 = tf.convert_to_tensor(tensor_2d_1)
m3 = tf.convert_to_tensor(tensor_2d_2)

# perform matrix operation on tensors
mat_product = tf.matmul(m1, m2)
mat_sum = tf.add(m2, m3)
mat_det = tf.matrix_determinant(m3)

# run session and see the results
with tf.Session() as session:
  print(session.run(mat_product))
  print(session.run(mat_sum))
  print(session.run(mat_det))

让我们运行代码:

我们已经在TensorFlow上尝试了一些矩阵运算,但是正弦,余弦之类的元素运算如何呢?好的过程保持不变,但是,如果我们对向量进行余弦运算,那么形成的结果将是元素化的。
让我们在一个示例的帮助下看到这一点:

import numpy as np
import tensorflow as tf

# Create a numpy array
tensor_1d = np.array([0, 0, 0])

# Convert to tensor
tensor = tf.convert_to_tensor(tensor_1d, dtype=tf.float64)

# Run and let's find cos of this tensor
with tf.Session() as session:
  print(session.run(tf.cos(tensor)))

现在,运行以下代码:

使用TensorFlow进行机器学习

我们将看一个最小的机器学习示例,以及如何使用TensorFlow处理线性回归之类的算法。

线性回归

线性回归是机器学习领域中广泛使用的算法。
该算法基于机器学习的两个重要概念:成本函数和梯度下降。

因此,让我们将此算法与TensorFlow一起使用:

import tensorflow as tf
import numpy as np

# Declare some imporant constants
test_data_size = 2000
iterations = 10000
learn_rate = 0.005
 
# Generate Test Values
def generate_test_values():
  train_x = []
  train_y = []
 
  for _ in range(test_data_size):
      x1 = np.random.rand()
      x2 = np.random.rand()
      x3 = np.random.rand()
      y_f = 2 * x1 + 3 * x2 + 7 * x3 + 4
      train_x.append([x1, x2, x3])
      train_y.append(y_f)
 
  return np.array(train_x), np.transpose([train_y])

# Create place holders for various values
x = tf.placeholder(tf.float32, [None, 3], name="x")
W = tf.Variable(tf.zeros([3, 1]), name="W")
b = tf.Variable(tf.zeros([1]), name="b")
y = tf.placeholder(tf.float32, [None, 1])
 
model = tf.add(tf.matmul(x, W), b)
# Compute cost function
cost = tf.reduce_mean(tf.square(y - model))
# Training Model
train = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost)
 
train_dataset, train_values = generate_test_values()
 
init = tf.global_variables_initializer()
 
with tf.Session() as session:
  session.run(init)
 
  for _ in range(iterations):
 
      session.run(train, feed_dict={
          x: train_dataset,
          y: train_values
      })
 
  print( "cost = {}".format(session.run(cost, feed_dict={
      x: train_dataset,
      y: train_values
  })))
 
  print( "W = {}".format(session.run(W)))
  print( "b = {}".format(session.run(b)))

让我们运行程序。
W和b的输出参数应与generate_test_values函数中定义的参数相同: