Tensorflow开发环境配置及其基本概念(4)

sess = tf.Session() my_array = np.array([[1., 3., 5., 7., 9.], [-2., 0., 2., 4., 6.], [-6., -3., 0., 3., 6.]]) x_vals = np.array([my_array, my_array + 1]) x_data = tf.placeholder(tf.float32, shape=(3, 5)) m1 = tf.constant([[1.], [0.], [-1.], [2.], [4.]]) m2 = tf.constant([[2.]]) a1 = tf.constant([[10.]]) prod1 = tf.matmul(x_data, m1) prod2 = tf.matmul(prod1, m2) add1 = tf.add(prod2, a1) for x_val in x_vals: print(sess.run(add1, feed_dict={x_data: x_val})) ---result [[ 102.] [ 66.] [ 58.]] [[ 114.] [ 78.] [ 70.]]

接下来我们来看下代码如何运行,placeholder 在运行时送入(feed in)数据,从计算图中可以看到,要执行Add操作,需要首先执行prod1,然后执行prod2,最后才执行Add操作。

Tensorflow开发环境配置及其基本概念

1.2.4. 矩阵操作

许多的算法依赖于矩阵的操作,Tensorflow给我们提供了非常方便,快捷的矩阵运算。

# 生成对角线矩阵 identity_matrix = tf.diag([1.0, 1.0, 1.0]) # 随机填充2行3列矩阵 A = tf.truncated_normal([2, 3]) # 填充5 到一个2行3列矩阵 B = tf.fill([2, 3], 5.0) # 填充三行两列的随机数矩阵 C = tf.random_uniform([3, 2]) # 将numpy的矩阵转换 D = tf.convert_to_tensor(np.array([[1., 2., 3.], [-3., -7., -1.], [0., 5., -2.]])) sess = tf.Session() print(sess.run(identity_matrix)) print(sess.run(A)) print(sess.run(B)) print(sess.run(C)) print(sess.run(D)) ---result [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]] [[ 0.08475778 -0.81952369 -0.40169609] [-0.6406377 -0.67895085 -1.13811123]] [[ 5. 5. 5.] [ 5. 5. 5.]] [[ 0.30655277 0.81441486] [ 0.68046188 0.64171898] [ 0.76518583 0.10888731]] [[ 1. 2. 3.] [-3. -7. -1.] [ 0. 5. -2.]]

1.2.5. 声明运算符

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/dbbba6cd1d252418e79a7f3bc771dfde.html