学习进度笔记-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) 赋值或者从其中获取数据

基本操作

1.打开Pycharm,选择Create New Project,创建名为jqxx的项目。

 

  2.重新配置解释器 

 

完整代码

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)

    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)

    result=sess.run(product)
    print(result)
View Code

3.具体步骤

在Python环境,使用import导入TensorFlow模块,别名为tf。

  1. import tensorflow as tf  
  2. import os  
  3. os.environ["CUDA_VISIBLE_DEVICES"]="0"  

4.构造计算图,创建两个常量节点a,b,值分别为2,3,代码如下:

  1. a=tf.constant(2)  
  2. b=tf.constant(3)  

5.创建一个Session会话对象,调用run方法,运行计算图。

  1. with tf.Session() as sess:  
  2. print("a:%i" % sess.run(a),"b:%i" % sess.run(b))  
  3. print("Addition with constants: %i" % sess.run(a+b))  
  4. print("Multiplication with constant:%i" % sess.run(a*b))  

6.使用变量Variable构造计算图a,b

  1. a=tf.placeholder(tf.int16)  
  2. b=tf.placeholder(tf.int16)  

7.使用tf中的add,multiply函数对a,b进行求和与求积操作。

  1. add=tf.add(a,b)  
  2. mul=tf.multiply(a,b)  

8.创建一个Session会话对象,调用run方法,运行计算图。

  1. with tf.Session() as sess:  
  2. print("Addition with variables: %i" % sess.run(add,feed_dict={a:2,b:3}))  
  3. print("Multiplication with variables: %i" % sess.run(mul,feed_dict={a:2,b:3}))  

9.构造计算图,创建两个矩阵常量节点matrix1,matrix2,值分别为[[3.,3.]],[[2.],[2.]],代码如下:

  1. matrix1=tf.constant([[3.,3.]])  
  2. matrix2=tf.constant([[2.],[2.]])  

10.构造矩阵乘法运算,

  1. product=tf.matmul(matrix1,matrix2)  

11.创建一个Session会话对象,调用run方法,运行计算图。

with tf.Session() as sess:

  1. result=sess.run(product)  
  2. print(result)  

12.运行结果:

 

原文地址:https://www.cnblogs.com/20183544-wangzhengshuai/p/14318113.html