在TensorFlow中使用矩阵
单位矩阵
import tensorflow as tf I_matrix=tf.eye(5) with tf.Session() as sess: print(sess.run(I_matrix))
variable矩阵
import tensorflow as tf X=tf.Variable(tf.eye(10)) A=tf.Variable(tf.random_normal([5,10])) with tf.Session() as sess: sess.run(X.initializer) print(sess.run(X)) sess.run(A.initializer) print(sess.run(A))
矩阵乘法
import tensorflow as tf X=tf.Variable(tf.eye(10)) A=tf.Variable(tf.random_normal([5,10])) product=tf.matmul(A,X) with tf.Session() as sess: sess.run(X.initializer) #print(sess.run(X)) sess.run(A.initializer) #print(sess.run(A)) print(sess.run(product))
创建一个只含有0,1的矩阵
import tensorflow as tf b=tf.Variable(tf.random_uniform([5,10],0,2,tf.int32)) with tf.Session() as sess: sess.run(b.initializer) print(sess.run(b))
矩阵加法
import tensorflow as tf A=tf.Variable(tf.random_normal([5,10])) b=tf.Variable(tf.random_uniform([5,10],0,2,tf.int32)) b_new=tf.cast(b,tf.float32) add=tf.add(A,b_new) sub=A-b_new with tf.Session() as sess: sess.run(A.initializer) sess.run(b.initializer) print(sess.run(A)) print(sess.run(b)) print(sess.run(add)) print(sess.run(sub))
剩下还有许多,如a和b是同类型矩阵时:
按元素相乘A=a*b
按元素相除A=tf.div(a,b)
按元素取余数A=tf.mod(a.b)
乘以一个标量A=tf.scalar_mul(2,a)