TensorFlow常用操作
初始化数据:
# -*- coding: utf-8 -*- import tensorflow as tf a = tf.zeros([3, 4], tf.int32) # [[0 0 0 0] # [0 0 0 0] # [0 0 0 0]] b = tf.zeros_like(a) #按照a的结构 # [[0 0 0 0] # [0 0 0 0] # [0 0 0 0]] c = tf.ones_like(a) #按照a的结构 # [[1 1 1 1] # [1 1 1 1] # [1 1 1 1]] d = tf.constant([1, 2, 3, 4, 5, 6, 7]) # [1 2 3 4 5 6 7] e = tf.constant(-1.0, shape=[2, 3]) # [[-1. -1. -1.] # [-1. -1. -1.]] f = tf.linspace(10.0, 12.0, 3, name="linspace") # [ 10. 11. 12.] g = tf.range(start=3, limit=18, delta=3) # [ 3 6 9 12 15] norm = tf.random_normal([2, 3], mean=-1, stddev=4,seed=1) #高斯分布 # [[ -4.24527264 4.93839502 -0.73868251] # [-10.7708168 -0.60300636 1.36489725]] c = tf.constant([[1, 2], [3, 4], [5, 6]]) #shuffle shuff = tf.random_shuffle(c) with tf.Session() as sess: print (sess.run(g))
循环打印:
# -*- coding: utf-8 -*- import tensorflow as tf state = tf.Variable(0) #初始化 new_value = tf.add(state, tf.constant(1)) #加一 update = tf.assign(state, new_value) #更新 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) #在会话里初始化全局变量 print(sess.run(state)) #打印state for _ in range(3): sess.run(update) #执行循环 print(sess.run(state)) #打印state # 0 # 1 # 2 # 3
numpy转TensorFlow格式:
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np a = np.zeros((3,3)) ta = tf.convert_to_tensor(a) with tf.Session() as sess: print(sess.run(ta)) # [[ 0. 0. 0.] # [ 0. 0. 0.] # [ 0. 0. 0.]]