tensorflow 的一些基本操作

本文介绍了TensorFlow的基础概念,包括张量、图计算、交互环境下的使用等。详细讲解了如何创建计算图、执行图计算,以及变量、占位符等核心组件的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.概览

2.图计算

3.交互环境下的使用

4.tensor

5.变量(variables)

6.抓取(fetch)

7.填充(feeds)


1.概览:

TensorFlow是一种将计算表示为图的编程系统。图中的节点称为ops(operation的简称)。一个ops使用0个或以上的Ten在TensorFlow中,Constant是一种没有输入的ops,但是你可以将它作为其他ops的输入。Python库中的ops构造器将返回构造器的输出。TensorFlow的Python库中有一个默认的图,将ops构造器作为节点,更多可了解Graph Class文档sors,通过执行某些运算,产生0个或以上的Tensors一个Tensor是一个多维数组,例如,你可以将一批图像表示为一个四维的数组[batch, height, width, channels],数组中的值均为浮点数。

TensorFlow中的图描述了计算过程,图通过Session的运行而执行计算。Session将图的节点们(即ops)放置到计算设备(如CPUs和GPUs)上,然后通过方法执行它们;这些方法执行完成后,将返回tensors。在Python中的tensor的形式是numpy ndarray对象,而在C/C++中则是tensorflow::Tensor.

2.图计算:

TensorFlow程序中图的创建类似于一个 [施工阶段],而在 [执行阶段] 则利用一个session来执行图中的节点。很常见的情况是,在 [施工阶段] 创建一个图来表示和训练神经网络,而在 [执行阶段] 在图中重复执行一系列的训练操作。

2.1.创建计算图:

在TensorFlow中,Constant是一种没有输入的ops,但是你可以将它作为其他ops的输入。Python库中的ops构造器将返回构造器的输出。TensorFlow的Python库中有一个默认的图,将ops构造器作为节点,更多可了解Graph Class文档

见下面的示例代码:

import tensorflow as tf

# Create a Constant op that produces a 1x2 matrix.  The op is
# added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
matrix1 = tf.constant([[3., 3.]])

# Create another Constant that produces a 2x1 matrix.
matrix2 = tf.constant([[2.],[2.]])

# Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
# The returned value, 'product', represents the result of the matrix
# multiplication.
product = tf.matmul(matrix1, matrix2)

默认的图(Default Graph)现在有了三个节点:两个 Constant()ops和一个matmul()op。为了得到这两个矩阵的乘积结果,还需要在一个session中启动图计算。

2.2.在Session中执行图计算:

见下面的示例代码:

# Launch the default graph.
sess = tf.Session()

# To run the matmul op we call the session 'run()' method, passing 'product'
# which represents the output of the matmul op.  This indicates to the call
# that we want to get the output of the matmul op back.
#
# All inputs needed by the op are run automatically by the session.  They
# typically are run in parallel.
#
# The call 'run(product)' thus causes the execution of threes ops in the
# graph: the two constants and matmul.
#
# The output of the op is returned in 'result' as a numpy `ndarray` object.
result = sess.run(product)
print(result)
# ==> [[ 12.]]

# Close the Session when we're done.
sess.close()

Sessions最后需要关闭,以释放相关的资源;你也可以使用with模块,session在with模块中自动会关闭:

with tf.Session() as sess:
  result = sess.run([product])
  print(result)

3.交互环境下的使用:

以上的python示例中,使用了SessionSession.run()来执行图计算。然而,在一些Python的交互环境下(如IPython中),你可以使用InteractiveSession类,以及Tensor.eval()Operation.run()等方法。例如,在交互的Python环境下执行以下代码:

# Enter an interactive TensorFlow Session.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# Initialize 'x' using the run() method of its initializer op.
x.initializer.run()

# Add an op to subtract 'a' from 'x'.  Run it and print the result
sub = tf.sub(x, a)
print(sub.eval())
# ==> [-2. -1.]

# Close the Session when we're done.
sess.close()

4.Tensors:

TensorFlow中使用tensor数据结构(实际上就是一个多维数据)表示所有的数据,并在图计算中的节点之间传递数据。

5.变量(Variables):

变量在图执行的过程中,保持着自己的状态信息。下面代码中的变量充当了一个简单的计数器角色:

# Create a Variable, that will be initialized to the scalar value 0.
state = tf.Variable(0, name="counter")

# Create an Op to add one to `state`.

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# Variables must be initialized by running an `init` Op after having
# launched the graph.  We first have to add the `init` Op to the graph.
init_op = tf.initialize_all_variables()

# Launch the graph and run the ops.
with tf.Session() as sess:
  # Run the 'init' op
  sess.run(init_op)
  # Print the initial value of 'state'
  print(sess.run(state))
  # Run the op that updates 'state' and print 'state'.
  for _ in range(3):
    sess.run(update)
    print(sess.run(state))

# output:

# 0
# 1
# 2
# 3

6.抓取(fetch):

TensorFlow也提供这样的机制:先创建特定数据类型的占位符(placeholder),之后再进行数据的填充。例如下面的程序:

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
  print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

# output:
# [array([ 14.], dtype=float32)]

7.填充(feeds):

TensorFlow也提供这样的机制:先创建特定数据类型的占位符(placeholder),之后再进行数据的填充。例如下面的程序:

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
  print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

# output:
# [array([ 14.], dtype=float32)]






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值