首先看一下张量计算:
import tensorflow as tf
a = tf.constant([1.0,2.0])
b = tf.constant([3.0,4.0])
result = a+b
print(result)
#输出:Tensor("add:0", shape=(2,), dtype=float32)
并没有打印出来相加的值,而是一个计算图,shape=(2,)表示这个结果张量的第一维有两个数(而不是说这两个数相加)。
如果你再加两个操作数:
c = tf.constant([3.0,4.0])
d = tf.constant([3.0,4.0])
result = a+b+c+d
打印结果:
Tensor("add_2:0", shape=(2,), dtype=float32)
由此可以看到,前面的add_2:0代表我们计算图中要加的个数,0——2+1 一共四个数
现在看乘法:
x = tf.constant([[1.0,2.0]])
w = tf.constant([[3.0],[4.0]])
y = tf.matmul(x,w)
print(y)
#Tensor("MatMul:0", shape=(1, 1), dtype=float32)
shape(1,1)很好的说明了结果张量的是1*1的矩阵
我们现在通过会话操作来进行计算:
with tf.Session() as sess:
print(sess.run(y))
#会话,用于节点运算
打印 [[11.]] 表示矩阵乘法的结果。
可能会报警告:
2020-02-26 21:33:53.023965: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-02-26 21:33:53.281393: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1432] Found device 0 with properties:
name: GeForce GTX 1070 with Max-Q Design major: 6 minor: 1 memoryClockRate(GHz): 1.2655
pciBusID: 0000:01:00.0
totalMemory: 8.00GiB freeMemory: 6.62GiB
2020-02-26 21:33:53.281672: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0
2020-02-26 21:33:54.071720: I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-02-26 21:33:54.071878: I tensorflow/core/common_runtime/gpu/gpu_device.cc:988] 0
2020-02-26 21:33:54.071965: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1001] 0: N
2020-02-26 21:33:54.072156: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 6382 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1070 with Max-Q Design, pci bus id: 0000:01:00.0, compute capability: 6.1)
Your CPU supports instructions that this TensorFlow binary was not compiled to use
说明你的计算机支持更高指令,但是Tensorflow并没有使用。这个警告可以不用管,想屏蔽的话参考网上的方法即可。