本文章只是学习笔记,不具有任何参考价值
学习网站:http://c.biancheng.net/view/1886.html
矩阵运算
- 随机矩阵
- 零矩阵
- 一矩阵
- 单位矩阵
实例
import tensorflow as tf
# 创建一个会话
sess = tf.InteractiveSession()
# 定义一个单位矩阵
Iden_matrix = tf.eye(5)
print(Iden_matrix.eval())
# 定义一个已经初始化的10X10的单位矩阵
A = tf.Variable(tf.eye(10))
A.initializer.run()
print(A.eval())
# 创建一个5X10随机矩阵
B = tf.Variable(tf.random_normal([5,10]))
B.initializer.run()
# 使两个矩阵相乘
result = tf.matmul(B,A)
print(result.eval())
# 创建一个0到1大小为5x10的随机矩阵
C = tf.Variable(tf.random_uniform([5,10],0,2,dtype = tf.int32))
C.initializer.run()
print(C.eval())
# 把C转化为32为浮点型矩阵
C_new = tf.cast(C,dtype = tf.float32)
# 把两个矩阵相加
sum = tf.add(result,C_new)
sub = result - C_new
print("B*A + C\n", sum.eval())
print("A*B - C\n",sub.eval())
输出
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
[[-1.0170325 0.44864097 0.26494917 0.33232278 0.9233874 -1.474763
0.95790523 -1.9321308 1.8650025 0.45929542]
[-1.683287 0.98936826 0.29436 2.7642577 -1.8612245 0.49307135
0.458501 0.08915332 1.7389778 -1.7772493 ]
[-0.22923784 -0.1535325 -0.1473962 1.4027133 -1.618484 -0.03005551
-0.43663406 0.82927006 -0.641992 0.919506 ]
[-1.1508818 0.78997105 0.5975108 0.7972655 1.5927783 0.25805026
-0.42002657 -1.3030639 1.2953455 -1.3883115 ]
[ 0.03349365 1.3132596 0.19996184 0.8860827 -0.4021669 -0.4833743
-0.7294122 -0.82327306 0.4480351 -1.1123691 ]]
[[0 1 0 1 1 1 1 0 0 0]
[1 0 0 0 1 1 0 0 0 1]
[0 1 1 1 0 1 0 1 0 1]
[0 0 1 0 1 1 1 1 1 0]
[0 0 1 0 0 0 0 1 0 1]]
B*A + C
[[-1.0170325 1.448641 0.26494917 1.3323228 1.9233874 -0.47476304
1.9579053 -1.9321308 1.8650025 0.45929542]
[-0.683287 0.98936826 0.29436 2.7642577 -0.86122453 1.4930713
0.458501 0.08915332 1.7389778 -0.77724934]
[-0.22923784 0.8464675 0.8526038 2.4027133 -1.618484 0.9699445
-0.43663406 1.8292701 -0.641992 1.9195061 ]
[-1.1508818 0.78997105 1.5975108 0.7972655 2.5927782 1.2580502
0.57997346 -0.30306387 2.2953455 -1.3883115 ]
[ 0.03349365 1.3132596 1.1999619 0.8860827 -0.4021669 -0.4833743
-0.7294122 0.17672694 0.4480351 -0.11236906]]
A*B - C
[[-1.0170325 -0.55135906 0.26494917 -0.6676772 -0.07661259 -2.474763
-0.04209477 -1.9321308 1.8650025 0.45929542]
[-2.6832871 0.98936826 0.29436 2.7642577 -2.8612247 -0.5069287
0.458501 0.08915332 1.7389778 -2.7772493 ]
[-0.22923784 -1.1535325 -1.1473962 0.4027133 -1.618484 -1.0300555
-0.43663406 -0.17072994 -0.641992 -0.08049399]
[-1.1508818 0.78997105 -0.4024892 0.7972655 0.5927783 -0.74194974
-1.4200265 -2.3030639 0.29534554 -1.3883115 ]
[ 0.03349365 1.3132596 -0.80003816 0.8860827 -0.4021669 -0.4833743
-0.7294122 -1.8232731 0.4480351 -2.112369 ]]
Process finished with exit code 0