python踩坑记1矩阵乘法

python踩坑记1矩阵乘法@TOC

本人自学的python,从照书抄代码,到看视频,上社区,踩了不少坑,其中有版本原因、有书写不规范,在此记录下来,也与各位新人共免,希望大虾们不要取笑才好。
1、tensorflow 张量运算问题
TensorFlow快速入门教程中矩阵相加问题

t_2 = tf.constant([4,3,2])
t_1 = tf.constant([1,2,3])
t=tf.add(t_1,t_2)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(t))

结果:runfile(‘D:/anaconda3/1/untitled1.py’, wdir=‘D:/anaconda3/1’)
[5 5 5]
很好,也很顺利。
运行乘法:multiply 没问题

import numpy as np
import tensorflow as tf
t_2 = tf.constant([4,3,1])
t_1 = tf.constant([[1],[2],[3]])
#t=tf.matmul(t_1,t_2)
t1=tf.multiply(t_1,t_2)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(t1))
  

[[ 4 3 1]
[ 8 6 2]
[12 9 3]]
#运行matmul,直接傻了

import numpy as np
import tensorflow as tf
t_2 = tf.constant([4,3,1])
t_1 = tf.constant([[1],[2],[3]])
t=tf.matmul(t_1,t_2)
#t1=tf.multiply(t_1,t_2)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(t))

ValueError: Shape must be rank 2 but is rank 1 for ‘MatMul_25’ (op: ‘MatMul’) with input shapes: [3,1], [3].
查了半天没搞明白,直接说格式对。后来发现t_2定义矩阵不对,改成
t_2 = tf.constant([[4,3,1]])搞定

import numpy as np
import tensorflow as tf
t_2 = tf.constant([[4,3,1]])
t_1 = tf.constant([[1],[2],[3]])
t=tf.matmul(t_1,t_2)
#t1=tf.multiply(t_1,t_2)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(t))

[[ 4 3 1]
[ 8 6 2]
[12 9 3]]
基础不牢的代价!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值