TensorFlow的简单实用
定义常量 import tensorflow as tf # 定义常量 m1 = tf.constant([[3, 3]]) m2 = tf.constant([[2], [3]]) # 定义乘法 product = tf.matmul(m1, m2) # 这里不会直接输出结果,会打印出一个tensor # 想要输出结果要在sess中进行 print(product) # 第一种方式定义session sess = tf.Session() result = sess.run(product) print(result) sess.close() # 第二种方式定义session with tf.Session() as sess: print(sess.run(product)) sess.close() 结果:[[15]] 定义变量 import tensorflow as tf # 定义变量 x = tf.Variable([1, 2]) y = tf.Variable([3, 3]) sub = tf.subtract(x, y) add = tf.add(x, y) # 初始化所有变量 对于变量要进行初始化 init = tf.global_variables_initializer() # 在回话中进行结果 with tf.Session() as sess: sess