TensorFlow简介

本文简要介绍了 张量流 库使用Python编程语言。

null

介绍

张量流 是一个开源软件库。 张量流 最初是由谷歌机器智能研究组织内谷歌大脑团队的研究人员和工程师开发的,目的是进行机器学习和深入的神经网络研究,但该系统具有足够的通用性,可以应用于其他广泛领域!

让我们先试着理解这个词是什么 张量流 我是说!

张量流 基本上是一个使用 数据流图 哪里:

  • 节点 在图中表示数学运算。
  • 边缘 图中表示多维数据数组(称为 张量 )他们之间的沟通。(请注意 张量 是TensorFlow中数据的中心单位)。

考虑下面给出的图表:

图片[1]-TensorFlow简介-yiteyi-C++库

在这里 添加 表示加法运算的节点。 A. B 是输入张量和 C 是合成张量。

这种灵活的体系结构允许您使用单个API将计算部署到桌面、服务器或移动设备中的一个或多个CPU或GPU!

TensorFlow API

张量流 提供多个API(应用程序编程接口)。这些可分为两大类:

  1. 低级API:
    • 完全编程控制
    • 推荐给机器学习研究人员
    • 提供对模型的精细控制
    • 张量流核 是TensorFlow的低级API。
  2. 高级API:
    • 建立在 张量流核
    • 比以前更容易学习和使用 张量流核
    • 让重复性任务在不同用户之间更容易、更一致
    • tf。contrib。学 是高级API的一个示例。

在本文中,我们首先讨论 张量流核 然后探索更高级别的API, tf。contrib。学 .

张量流核

1.安装TensorFlow

一个简单易懂的指南 张量流 可在以下位置进行安装: 安装TensorFlow .

安装后,可以通过在python解释器中运行以下命令来确保成功安装:

import tensorflow as tf

2.计算图

任何 张量流核 程序可分为两个独立的部分:

  • 构建计算图。A. 计算图 只不过是一系列排列成节点图的TensorFlow操作。
  • 运行计算图表。为了实际评估节点,我们必须在 一场 .会话封装TensorFlow运行时的控件和状态。

现在,让我们写下我们的第一篇文章 张量流 了解上述概念的程序:

# importing tensorflow
import tensorflow as tf
# creating nodes in computation graph
node1 = tf.constant( 3 , dtype = tf.int32)
node2 = tf.constant( 5 , dtype = tf.int32)
node3 = tf.add(node1, node2)
# create tensorflow session object
sess = tf.Session()
# evaluating node3 and printing the result
print ( "Sum of node1 and node2 is:" ,sess.run(node3))
# closing the session
sess.close()


输出:

Sum of node1 and node2 is: 8

让我们试着理解上面的代码:

  • 第一步:创建计算图 通过创建计算图,我们指的是定义节点。Tensorflow为各种任务提供了不同类型的节点。每个节点将零个或多个张量作为输入,并生成一个张量作为输出。
    • 在上面的程序中,节点 点头1 点头2 属于 tf。常数 类型A. 常数 节点不接受任何输入,并输出其内部存储的值。注意,我们还可以使用 数据类型 论点
      node1 = tf.constant(3, dtype=tf.int32)
      node2 = tf.constant(5, dtype=tf.int32)
      
    • 点头3 是的 tf。添加 类型它将两个张量作为输入,并将它们的和作为输出张量返回。
      node3 = tf.add(node1, node2)
      
  • 第2步:运行计算图 为了运行计算图,我们需要创建一个 一场 .要创建会话,我们只需执行以下操作:
    sess = tf.Session()
    

    现在,我们可以调用 会话对象在任何节点上执行计算的方法:

    print("Sum of node1 and node2 is:",sess.run(node3))
    

    在这里 点头3 获取进一步调用的 点头1 点头2 .最后,我们使用以下方法结束会话:

    sess.close()
    

注: 另一种(也是更好的)处理会话的方法是使用 用积木 这样地:

with tf.Session() as sess:
    print("Sum of node1 and node2 is:",sess.run(node3))

这种方法的好处是,您不需要显式关闭会话,因为一旦控制超出范围,会话就会自动关闭 具有

3.变量

TensorFlow 变量 也可以保存变量数据的节点。它们主要用于保存和更新训练模型的参数。

变量是 内存缓冲区 包含张量。它们必须显式初始化,并可在培训期间和培训后保存到磁盘。以后可以恢复保存的值以练习或分析模型。

需要注意的一个重要区别是 常数 变量 是:

常量的值存储在图形中,其值会复制到图形加载的任何位置。变量是单独存储的,可以存在于参数服务器上。

下面是一个使用 变量 :

# importing tensorflow
import tensorflow as tf
# creating nodes in computation graph
node = tf.Variable(tf.zeros([ 2 , 2 ]))
# running computation graph
with tf.Session() as sess:
# initialize all global variables
sess.run(tf.global_variables_initializer())
# evaluating node
print ( "Tensor value before addition:" ,sess.run(node))
# elementwise addition to tensor
node = node.assign(node + tf.ones([ 2 , 2 ]))
# evaluate node again
print ( "Tensor value after addition:" , sess.run(node))


输出:

Tensor value before addition:
 [[ 0.  0.]
 [ 0.  0.]]
Tensor value after addition:
 [[ 1.  1.]
 [ 1.  1.]]

在上述计划中:

  • 我们定义一个类型为 变量 并赋予它一些初始值。
    node = tf.Variable(tf.zeros([2,2]))
    
  • 要在当前会话的作用域中初始化变量节点,我们需要执行以下操作:
    sess.run(tf.global_variables_initializer())
    
  • 要给变量节点分配一个新值,我们可以使用 分配 方法如下:
    node = node.assign(node + tf.ones([2,2]))
    

4.占位符

图形可以参数化以接受外部输入,称为 占位符 .占位符是承诺以后提供值。

在计算涉及 占位符 节点,a 饮食习惯 参数传递给会话的 方法指定为这些占位符提供具体值的张量。

考虑下面给出的例子:

# importing tensorflow
import tensorflow as tf
# creating nodes in computation graph
a = tf.placeholder(tf.int32, shape = ( 3 , 1 ))
b = tf.placeholder(tf.int32, shape = ( 1 , 3 ))
c = tf.matmul(a,b)
# running computation graph
with tf.Session() as sess:
print (sess.run(c, feed_dict = {a:[[ 3 ],[ 2 ],[ 1 ]], b:[[ 1 , 2 , 3 ]]}))


输出:

[[3 6 9]
 [2 4 6]
 [1 2 3]]

让我们试着了解一下上述计划:

  • 我们定义占位符节点 A. B 这样地:
    a = tf.placeholder(tf.int32, shape=(3,1))
    b = tf.placeholder(tf.int32, shape=(1,3))
    

    第一个参数是张量的数据类型,可选参数之一是张量的形状。

  • 我们定义另一个节点 C 矩阵乘法的运算是什么( 马特穆尔 ).我们将两个占位符节点作为参数传递。
    c = tf.matmul(a,b)
    
  • 最后,当我们运行会话时,我们将占位符节点的值传递给 饮食习惯 争论 塞斯。跑 :
    print(sess.run(c, feed_dict={a:[[3],[2],[1]], b:[[1,2,3]]}))
    

    考虑下面的图表来明确这个概念:

  • 最初: 图片[2]-TensorFlow简介-yiteyi-C++库
  • 赛斯之后。运行: 图片[3]-TensorFlow简介-yiteyi-C++库

5.一个例子:线性回归模型

下面给出了一个 线性回归模型 使用TensorFlow核心API。

# importing the dependencies
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Model Parameters
learning_rate = 0.01
training_epochs = 2000
display_step = 200
# Training Data
train_X = np.asarray([ 3.3 , 4.4 , 5.5 , 6.71 , 6.93 , 4.168 , 9.779 , 6.182 , 7.59 , 2.167 ,
7.042 , 10.791 , 5.313 , 7.997 , 5.654 , 9.27 , 3.1 ])
train_y = np.asarray([ 1.7 , 2.76 , 2.09 , 3.19 , 1.694 , 1.573 , 3.366 , 2.596 , 2.53 , 1.221 ,
2.827 , 3.465 , 1.65 , 2.904 , 2.42 , 2.94 , 1.3 ])
n_samples = train_X.shape[ 0 ]
# Test Data
test_X = np.asarray([ 6.83 , 4.668 , 8.9 , 7.91 , 5.7 , 8.7 , 3.1 , 2.1 ])
test_y = np.asarray([ 1.84 , 2.273 , 3.2 , 2.831 , 2.92 , 3.24 , 1.35 , 1.03 ])
# Set placeholders for feature and target vectors
X = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
# Set model weights and bias
W = tf.Variable(np.random.randn(), name = "weight" )
b = tf.Variable(np.random.randn(), name = "bias" )
# Construct a linear model
linear_model = W * X + b
# Mean squared error
cost = tf.reduce_sum(tf.square(linear_model - y)) / ( 2 * n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
# Load initialized variables in current session
sess.run(init)
# Fit all training data
for epoch in range (training_epochs):
# perform gradient descent step
sess.run(optimizer, feed_dict = {X: train_X, y: train_y})
# Display logs per epoch step
if (epoch + 1 ) % display_step = = 0 :
c = sess.run(cost, feed_dict = {X: train_X, y: train_y})
print ( "Epoch:{0:6} Cost:{1:10.4} W:{2:6.4} b:{3:6.4}" .
format (epoch + 1 , c, sess.run(W), sess.run(b)))
# Print final parameter values
print ( "Optimization Finished!" )
training_cost = sess.run(cost, feed_dict = {X: train_X, y: train_y})
print ( "Final training cost:" , training_cost, "W:" , sess.run(W), "b:" ,
sess.run(b), '' )
# Graphic display
plt.plot(train_X, train_y, 'ro' , label = 'Original data' )
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label = 'Fitted line' )
plt.legend()
plt.show()
# Testing the model
testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / ( 2 * test_X.shape[ 0 ]),
feed_dict = {X: test_X, y: test_y})
print ( "Final testing cost:" , testing_cost)
print ( "Absolute mean square loss difference:" , abs (training_cost - testing_cost))
# Display fitted line on test data
plt.plot(test_X, test_y, 'bo' , label = 'Testing data' )
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label = 'Fitted line' )
plt.legend()
plt.show()


Epoch:   200      Cost:    0.1715      W: 0.426      b:-0.4371
Epoch:   400      Cost:    0.1351      W:0.3884      b:-0.1706
Epoch:   600      Cost:    0.1127      W:0.3589      b:0.03849
Epoch:   800      Cost:   0.09894      W:0.3358      b:0.2025
Epoch:  1000      Cost:   0.09047      W:0.3176      b:0.3311
Epoch:  1200      Cost:   0.08526      W:0.3034      b:0.4319
Epoch:  1400      Cost:   0.08205      W:0.2922      b:0.5111
Epoch:  1600      Cost:   0.08008      W:0.2835      b:0.5731
Epoch:  1800      Cost:   0.07887      W:0.2766      b:0.6218
Epoch:  2000      Cost:   0.07812      W:0.2712      b:  0.66
Optimization Finished!
Final training cost: 0.0781221 W: 0.271219 b: 0.65996 

图片[4]-TensorFlow简介-yiteyi-C++库

Final testing cost: 0.0756337
Absolute mean square loss difference: 0.00248838

图片[5]-TensorFlow简介-yiteyi-C++库

让我们试着理解上面的代码。

  • 首先,我们定义一些参数来训练我们的模型,比如:
    learning_rate = 0.01
    training_epochs = 2000
    display_step = 200
    
  • 然后定义特征和目标向量的占位符节点。
    X = tf.placeholder(tf.float32)
    y = tf.placeholder(tf.float32)
    
  • 然后,我们为权重和偏差定义可变节点。
    W = tf.Variable(np.random.randn(), name="weight")
    b = tf.Variable(np.random.randn(), name="bias")
    
  • 线性模型 是计算线性回归模型假设的操作节点。
    linear_model = W*X + b
    
  • 每次梯度下降的损失(或成本)计算为均方误差,其节点定义为:
    cost = tf.reduce_sum(tf.square(linear_model - y)) / (2*n_samples)
    
  • 最后,我们有了 优化器 实现梯度下降算法的节点。
    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
    
  • 现在,通过应用梯度下降算法将训练数据拟合到线性模型中。任务是重复的 训练时代 次数。在每个历元中,我们执行梯度下降步骤如下:
    sess.run(optimizer, feed_dict={X: train_X, y: train_y})
    
  • 以后 显示步骤 根据历元数,我们打印电流损耗值,该值可通过以下方式找到:
    c = sess.run(cost, feed_dict={X: train_X, y: train_y})
    
  • 根据试验数据和数据对模型进行了评估 测试成本 使用以下公式计算:
    testing_cost = sess.run(tf.reduce_sum(tf.square(linear_model - y)) / (2 * test_X.shape[0]),
                              feed_dict={X: test_X, y: test_y})
    

tf。contrib。学

tf。contrib。学 是一个高级TensorFlow库,可简化机器学习机制,包括以下内容:

  • 跑步训练循环
  • 运行评估循环
  • 管理数据集
  • 管理喂养

让我们试着看看线性回归在上面使用的相同数据上的实现 tf。contrib。学 .

# importing the dependencies
import tensorflow as tf
import numpy as np
# declaring list of features
features = [tf.contrib.layers.real_valued_column( "X" )]
# creating a linear regression estimator
estimator = tf.contrib.learn.LinearRegressor(feature_columns = features)
# training and test data
train_X = np.asarray([ 3.3 , 4.4 , 5.5 , 6.71 , 6.93 , 4.168 , 9.779 , 6.182 , 7.59 , 2.167 ,
7.042 , 10.791 , 5.313 , 7.997 , 5.654 , 9.27 , 3.1 ])
train_y = np.asarray([ 1.7 , 2.76 , 2.09 , 3.19 , 1.694 , 1.573 , 3.366 , 2.596 , 2.53 , 1.221 ,
2.827 , 3.465 , 1.65 , 2.904 , 2.42 , 2.94 , 1.3 ])
test_X = np.asarray([ 6.83 , 4.668 , 8.9 , 7.91 , 5.7 , 8.7 , 3.1 , 2.1 ])
test_y = np.asarray([ 1.84 , 2.273 , 3.2 , 2.831 , 2.92 , 3.24 , 1.35 , 1.03 ])
# function to feed dict of numpy arrays into the model for training
input_fn = tf.contrib.learn.io.numpy_input_fn({ "X" :train_X}, train_y,
batch_size = 4 , num_epochs = 2000 )
# function to feed dict of numpy arrays into the model for testing
test_input_fn = tf.contrib.learn.io.numpy_input_fn({ "X" :test_X}, test_y)
# fit training data into estimator
estimator.fit(input_fn = input_fn)
# print value of weight and bias
W = estimator.get_variable_value( 'linear/X/weight' )[ 0 ][ 0 ]
b = estimator.get_variable_value( 'linear/bias_weight' )[ 0 ]
print ( "W:" , W, " b:" , b)
# evaluating the final loss
train_loss = estimator.evaluate(input_fn = input_fn)[ 'loss' ]
test_loss = estimator.evaluate(input_fn = test_input_fn)[ 'loss' ]
print ( "Final training loss:" , train_loss)
print ( "Final testing loss:" , test_loss)


W: 0.252928     b: 0.802972
Final training loss: 0.153998
Final testing loss: 0.0777036

让我们试着理解上面的代码。

  • 特征矩阵的形状和类型使用列表声明。列表中的每个元素都定义了列的结构。在上面的例子中,我们只有一个功能,它存储实际值,并被命名 十、 .
    features = [tf.contrib.layers.real_valued_column("X")]
    
  • 然后,我们需要一个估计器。估计器只是一个预定义的模型,包含许多有用的方法和参数。在上面的例子中,我们使用线性回归模型估计器。
    estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
    
  • 出于训练目的,我们需要使用一个输入函数,该函数负责在训练时向估计器提供数据。它将特征列值作为字典。可以指定许多其他参数,如批量大小、历元数等。
    input_fn = tf.contrib.learn.io.numpy_input_fn({"X":train_X}, 
                  train_y, batch_size=4, num_epochs=2000)
    
  • 为了使训练数据与估计器相匹配,我们只需使用 适合 输入函数作为参数传递的估计方法。
    estimator.fit(input_fn=input_fn)
    
  • 一旦训练完成,我们可以使用 获取变量值 估计方法。您可以使用 获取变量名 方法
    W = estimator.get_variable_value('linear/X/weight')[0][0]
    b = estimator.get_variable_value('linear/bias_weight')[0]
    
  • 均方误差/损失可计算为:
    train_loss = estimator.evaluate(input_fn=input_fn)['loss']
    test_loss = estimator.evaluate(input_fn=test_input_fn)['loss']
    

这就结束了 TensorFlow简介 文章

从这里,您可以尝试探索本教程: MNIST面向ML初学者 .

本文由 尼希尔·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享