第一个TensorFlow的简单例子
使用TensorFlow进行一个简单的矩阵相加操作,并输出其结果。
import tensorflow as tf v_1=tf.constant([1,2,3,4]) v_2=tf.constant([2,1,5,3]) v_add=tf.add(v_1,v_2) with tf.Session() as sess: print(sess.run([v_1,v_2,v_add]))
结果截图:
较复杂的矩阵运算(相乘、相加):
import tensorflow as tf x=tf.constant([0.9,0.85],shape=[1,2]) w1=tf.Variable(tf.constant([[0.2,0.1,0.3],[0.2,0.4,0.3]],shape=[2,3],name="w1")) w2=tf.Variable(tf.constant([0.2,0.5,0.25],shape=[3,1],name="w2")) b1=tf.constant([-0.3,0.1,0.2],shape=[1,3],name="b1") b2=tf.constant([-0.3],shape=[1],name="b2") #初始化 init_op=tf.global_variables_initializer() a=tf.matmul(x,w1)+b1 y=tf.matmul(a,w2)+b2 with tf.Session() as sess: sess.run(init_op) print(sess.run(y))
输出结果截图: