真的很粗心啊!!刚玩Tensorflow总是会犯这种低级错误!
转载地址:https://blog.youkuaiyun.com/weixin_42147780/article/details/81117734
只要明确如下两句话基本可以摆脱这种小毛病。
1.TensorFlow用张量这种数据结构来表示所有的数据。
2.一个二阶张量就是我们平常所说的矩阵,一阶张量可以认为是一个向量。
如果不细心就总是会报错上面的错误!
扔代码:
import tensorflow as tf
#这个是矩阵的乘,位置交换不可以
matrix1 = tf.constant([[3.,3.]]) #两对中括号 [[ ]] ,这里是矩阵。少了一对中括号就变成向量了
matrix2 = tf.constant([[2.],[2.]])
result1 = tf.matmul(matrix1,matrix2) #矩阵乘法tf.matmul()
result2 = tf.matmul(matrix2,matrix1)
#这个是向量的乘,位置交换没关系
vector1 = tf.constant([3.,3.]) #这里只有一对中括号 [],就是向量!
vector2 = tf.constant([1.,2.])
result3 = tf.multiply(vector1,vector2) #向量乘法。tf.multiply()
result4 = tf.multiply(vector2,vector1)
sess = tf.Session()
r1 = sess.run(result1)
r2 = sess.run(result2)
r3 = sess.run(result3)
r4 = sess.run(result4)
print("print the matrix result")
print(r1,'\n',r2)
print("print the vector result")
print(r3,'\n',r4)