pip3 install tensorflow
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)
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)
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)
tf.placeholder(dtype, shape=None, name=None):占位符没有初始值,但必须指定类型数组
参数:数据结构
dtype:数据类型,tf.int32,float32,string等dom
shape:数据形状,默认None,shape=1,shape=[2,3],shape=[None,3]fetch
name:名称spa
返回:Tensor类型code
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}))