摘要:本文主要向大家介绍了机器学习入门之tensorflow——创建和操控张量,通过具体的内容向大家展现,希望对大家学习机器学习入门有所帮助。
本文主要向大家介绍了机器学习入门之tensorflow——创建和操控张量,通过具体的内容向大家展现,希望对大家学习机器学习入门有所帮助。
TensorFlow 的名称源自张量,张量是任意维度的数组。借助 TensorFlow,您可以操控具有大量维度的张量。即便如此,在大多数情况下,您会使用以下一个或多个低维张量:
标量是零维数组(零阶张量)。例如,\‘Howdy\‘ 或 5
矢量是一维数组(一阶张量)。例如,[2, 3, 5, 7, 11] 或 [5]
矩阵是二维数组(二阶张量)。例如,[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]
TensorFlow 指令会创建、销毁和操控张量。典型 TensorFlow 程序中的大多数代码行都是指令。
TensorFlow 图(也称为计算图或数据流图)是一种图数据结构。很多 TensorFlow 程序由单个图构成,但是 TensorFlow 程序可以选择创建多个图。图的节点是指令;图的边是张量。张量流经图,在每个节点由一个指令操控。一个指令的输出张量通常会变成后续指令的输入张量。TensorFlow 会实现延迟执行模型,意味着系统仅会根据相关节点的需求在需要时计算节点。
张量可以作为常量或变量存储在图中。您可能已经猜到,常量存储的是值不会发生更改的张量,而变量存储的是值会发生更改的张量。不过,您可能没有猜到的是,常量和变量都只是图中的一种指令。常量是始终会返回同一张量值的指令。变量是会返回分配给它的任何张量的指令。
要定义常量,请使用 tf.constant 指令,并传入它的值。例如:
x = tf.constant([5.2])
同样,您可以创建如下变量:
y = tf.Variable([5])
或者,您也可以先创建变量,然后再如下所示地分配一个值(注意:您始终需要指定一个默认值):
y = tf.Variable([0])
y = y.assign([5])
定义一些常量或变量后,您可以将它们与其他指令(如 tf.add)结合使用。在评估 tf.add 指令时,它会调用您的 tf.constant 或 tf.Variable 指令,以获取它们的值,然后返回一个包含这些值之和的新张量。
图必须在 TensorFlow 会话中运行,会话存储了它所运行的图的状态:
将 tf.Session() 作为会话:
initialization = tf.global_variables_initializer()
print y.eval()
在使用 tf.Variable 时,您必须在会话开始时调用 tf.global_variables_initializer,以明确初始化这些变量,如上所示。
简单DEMO:
import tensorflow as tf
with tf.Graph().as_default():
# Task 2: Simulate 10 throws of two dice. Store the results
# in a 10x3 matrix.
# We‘re going to place dice throws inside two separate
# 10x1 matrices. We could have placed dice throws inside
# a single 10x2 matrix, but adding different columns of
# the same matrix is tricky. We also could have placed
# dice throws inside two 1-D tensors (vectors); doing so
# would require transposing the result.
dice1 = tf.Variable(tf.random_uniform([10, 1],
minval=1, maxval=7,
dtype=tf.int32))
dice2 = tf.Variable(tf.random_uniform([10, 1],
minval=1, maxval=7,
dtype=tf.int32))
# We may add dice1 and dice2 since they share the same shape
# and size.
dice_sum = tf.add(dice1, dice2)
# We‘ve got three separate 10x1 matrices. To produce a single
# 10x3 matrix, we‘ll concatenate them along dimension 1.
resulting_matrix = tf.concat(
values=[dice1, dice2, dice_sum], axis=1)
with tf.Session() as sess:
# The variables haven‘t been initialized within the graph yet,
# so let‘s remedy that.
sess.run(tf.global_variables_initializer())
print(resulting_matrix.eval())
View Code
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标人工智能机器学习频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号