作者:半宅半学 | 来源:互联网 | 2023-06-07 04:14
开发者峰会:TensorflowLite
中文官网:https://tensorflow.google.cn/
中文社区:http://www.tensorfly.cn/
一、常量与变量
import tensorflow as tf
import numpy as np
print(tf.__version__)#变量定义的几种方法
def var_demo():# 1tha = tf.Variable(tf.linspace(-5.,5.,10),dtype=tf.float32)# 2thb = tf.Variable(tf.random_normal([3,3], mean=1.0,stddev=2.0, dtype=tf.float32), dtype=tf.float32)# 3thc = tf.Variable(b.initialized_value(), dtype=tf.float32)# 4thd = tf.Variable(tf.zeros([3,3], dtype=tf.float32), dtype=tf.float32)# 5the = tf.assign(a, tf.linspace(-1.,1.,10))f = tf.cast(e, dtype=tf.int32)c1 = tf.constant(3)c2 = tf.constant([2,3])# 初始化方式init = tf.global_variables_initializer()sess = tf.Session()sess.run(init)print(sess.run(a))print(sess.run(b))print(sess.run(c))print(sess.run(d))print(sess.run(e))print(sess.run(f))print(sess.run(c1))print(sess.run(c2))var_demo()
二、操作数与占位符
import tensorflow as tf
import numpy as np
print(tf.__version__)def ops_demo():a = tf.constant([[1, 2, 3], [4, 5, 6]])b = tf.constant(4)c = tf.Variable(tf.random_normal([2,3], 1.0,3.0), dtype=tf.float32)d = tf.add(c, tf.cast(tf.divide(a, b), dtype=tf.float32))m1 = tf.Variable(tf.random_normal([3, 3], 1.0, 3), dtype=tf.float32)m2 = tf.Variable(tf.random_normal([3, 3], 3.0, 1), dtype=tf.float32)m3 = tf.add(m1, m2)m4 = tf.subtract(m1, m2)m5 = tf.divide(m1, m2)m6 = tf.multiply(m1, m2)mm = tf.matmul(m1, m2)x = tf.placeholder(shape=[3,3], dtype=tf.float32)y = tf.placeholder(shape=[3,2], dtype=tf.float32)xy = tf.matmul(x, y)#初始化init = tf.global_variables_initializer()sess = tf.Session()sess.run(init)xy_result = sess.run(xy, feed_dict={x: [[1,1,1], [2,2,2],[3,3,3]], y:[[4,4],[5,5],[6,6]]})print(xy_result)ops_demo()