一、Tensorflow新手入门

1、MacOS Tensorflow(CPU版本)下载和安装

pip3 install tensorflow

2、Tensorflow的基本用法

  • 使用图(graph)来表示计算任务
  • 在回话(Session)的上下文(context)中执行图
  • 使用tensor表示数据
  • 通过变量(Variable)维护状态
  • 使用feed和fetch可以为任意的操作赋值或者从中获取数据

  综述:Tensorflow图中的节点称为op(operation),一个op获得o个或者多个tensor(数据)来执行计算,产生0个或者多个tensor(数据),每个tensor是一个类型化的多维数组

  计算图:Tensorflow程序通常分为构建阶段和执行阶段,构建阶段:op的执行步骤被描述成一个图,执行阶段:使用回话执行图中的op

  构建图:构建图的第一步是创建源op(源op不需要任何输入,如常量Constant),源op的输出被传递给其它op做运算。Tensorflow Python库有一个默认图,op构造器可以为图增加节点

import tensorflow as tf

# 创建一个常量op(节点),产生一个1X2矩阵
# 添加到默认图中
# 构造器的返回值代表该常量的op的返回值
matrix1 = tf.constant([[3., 3.]])

# 创建一个常量op(节点),产生一个2X1矩阵
matrix2 = tf.constant([[2.],[2.]])

# 创建一个矩阵乘法matmul op,把matrix1和matrix2作为输入
# 返回值product代表矩阵乘法的结果

product = tf.matmul(matrix1, matrix2)

# 启动默认图
# 调用sess的run()方法来执行矩阵乘法的op,传入值为product,输出矩阵的乘法op
# 返回值是一个numpy.ndarray对象
with tf.Session() as sess:
    result = sess.run(product)
    print(type(result),result)

  调用CPU或者GPU:一般不需要显示指定CPU或者GPU,Tensorflow能自动检测,使用找到的第一个来计算,如果机器上有超过一个可用的,为来让tensorflow使用,必须将op明确指派给它们执行。

with tf.Session() as sess:
    with tf.device(\'/gpu:1\'):
        matrix1 = tf.constant([[3., 3.]])
        matrix2 = tf.constant([[2.], [2.]])
        product = tf.matmul(matrix1, matrix2)
  • \'/cpu:0\':机器的cpu
  • \'/gpu:0\':机器的第一个gpu
  • \'/gpu:1\':机器的第二个gpu
  • ....

  Tensor:Tensorflow程序使用tensor数据结构来代表数据,可以把tensor看成一个n维数组或者列表,tensor包含静态类型rank和shape

  变量:Variable维护图执行过程中的状态

import tensorflow as tf

# 创建变量,初始化为标量0
state = tf.Variable(0, name=\'counter\')

# 创建一个op,使state增加1
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# 初始所有化变量
init_op = tf.global_variables_initializer()

# 启动图,运行op
with tf.Session() as sess:
    # 运行init
    sess.run(init_op)
    print(sess.run(state))
    for _ in range(3):
        sess.run(update)
        print(\'new_value:\',sess.run(new_value))
        print(\'state:\',sess.run(state))
import tensorflow as tf

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

intermed = tf.add(input2, input3)
mul = tf.multiply(input1, intermed)

with tf.Session() as sess:
    result = sess.run([mul, intermed])
    print(result)

Feed_dict和tf.placeholder:

  tf.placeholder(dtype, shape=None, name=None):占位符没有初始值,但必须指定类型

    参数:

      dtype:数据类型,tf.int32,float32,string等

      shape:数据形状,默认None,shape=1,shape=[2,3],shape=[None,3]

      name:名称

    返回:Tensor类型

  feed_dict:字典,给出placeholder的值

import tensorflow as tf
import numpy as np
# exp-1 x = tf.placeholder(tf.string) with tf.Session() as sess: output = sess.run(x, feed_dict={x: \'Hello World!\'}) print(output) # exp-2 x = tf.placeholder(tf.string) y = tf.placeholder(tf.int32) z = tf.placeholder(tf.float32) with tf.Session() as sess: output = sess.run([x,y,z], feed_dict={x: \'Hello World!\', y:1, z:0.1}) print(output)
# exp-3 x = tf.placeholder(tf.float32, shape=(None,3)) y = tf.matmul(x, x) with tf.Session() as sess: rand_array = np.random.rand(3,3) print(sess.run(y, feed_dict={x: rand_array}))