zoukankan      html  css  js  c++  java
  • 2021寒假(23)

    TensorFlow基本操作

    实验原理

    TensorFlow 是一个编程系统,使用图来表示计算任务,图中的节点被称之为 op (operation 的缩写)。一个 op 获得 0 个或多个 Tensor,执行计算产生 0 个或多个 Tensor。每个 Tensor 是一个类型化的多维数组。例如,你可以将一小组图像集表示为一个四维浮点数数组,这四个维度分别是 [batch, height, width, channels]。

    一个 TensorFlow 图描述了计算的过程,为了进行计算,图必须在会话里被启动。会话将图的 op 分发到诸如 CPU 或 GPU 之类的设备上,同时提供执行 op 的方法,这些方法执行后将产生的 tensor 返回。在 Python 语言中返回的 tensor 是 numpy ndarray 对象;在 C 和 C++ 语言中返回的 tensor 是 tensorflow::Tensor 实例。

    TensorFlow 程序通常被组织成一个构建阶段和一个执行阶段。在构建阶段,op 的执行步骤被描述成一个图;在执行阶段,使用会话执行图中的 op。

    使用 TensorFlow,你必须明白 TensorFlow的组件作用:

    • 使用图 (graph) 来表示计算任务
    • 在被称之为会话 (Session) 的上下文 (context) 中执行图
    • 使用 tensor 表示数据
    • 通过变量 (Variable) 维护状态
    • 使用 feed fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据
      import tensorflow as tf
      import os
      os.environ["CUDA_VISIBLE_DEVICES"]="0"
      a = tf.constant(2)
      b = tf.constant(3)
      with tf.Session() as sess:
          print("a:%i" % sess.run(a), "b:%i" % sess.run(b))
          print("Addition with constants: %i" % sess.run(a + b))
          print("Multiplication with constant:%i" % sess.run(a * b))
      
      a = tf.placeholder(tf.int16)
      b = tf.placeholder(tf.int16)
      add = tf.add(a,b)
      mul = tf.multiply(a,b)
      with tf.Session() as sess:
          print("Addition with variables: %i" % sess.run(add,feed_dict={a:2,b:3}))
          print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))
      
      matrix1=tf.constant([[3.,3.]])
      matrix2=tf.constant([[2.],[2.]])
      product=tf.matmul(matrix1,matrix2)
      with tf.Session() as sess:
          result=sess.run(product)
          print(result)
      

       结果截图:

     

  • 相关阅读:
    《1024伐木累》-小白篇之月侠-总章节五
    《1024伐木累-周末特别篇》-中彩票了,开发APP
    《1024伐木累》-有话直说,蛋疼~
    《1024伐木累》- 老王请客吃晚饭,介绍对象
    《1024伐木累》-小白篇之丽姐(前篇)-总章节四
    程序员最值得听的歌曲TOP10
    《1024伐木累》-职位不分贵贱,没房子怎么乐
    偶是一只别人眼里的程序猿
    《1024伐木累》-写代码写的娘炮了
    《1024伐木累》-小白篇之加班(结束篇)-总章节三
  • 原文地址:https://www.cnblogs.com/ywqtro/p/14383585.html
Copyright © 2011-2022 走看看