ValueError:形状必须为2级,但输入形状为[6],[6]的“ MatMul”(操作:“ MatMul”)为1级

时间:2019-02-15 06:35:13

标签: tensorflow

错误:

ValueError:形状必须为2级,但输入形状为[6],[6]的“ MatMul”(操作数:“ MatMul”)为1级。

import tensorflow as tf

with tf.device('/gpu:1'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
    c = tf.matmul(a, b)

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))

我不知道怎么了。非常感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

tf.matmul乘以二维张量的矩阵。您正在尝试使用matmul乘以两个向量,它们是一维张量。

您的预期结果是[ 1. 4. 9. 16. 25. 36.],即向量元素的元素乘法。要获得它,您必须使用tf.multiply操作。

import tensorflow as tf

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name="a")
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name="b")
c = tf.multiply(a, b)

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))

答案 1 :(得分:0)

否则,如果要进行矩阵乘法,而不是像其他答案中建议的那样进行元素乘法,则需要将矢量与列矢量进行二维乘以行矢量:

@Entity
@Table(name="users")
public class User extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "username")
    private String userName;

    @Column(name = "password")
    private String password;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Collection<Role> roles;

    ??????
    private List<Appointment> appointments;

    @ManyToMany
    @JoinTable(name="works_providers", joinColumns=@JoinColumn(name="id_user"), inverseJoinColumns=@JoinColumn(name="id_work"))
    private List<Work> works;

}

答案 2 :(得分:0)

您可以使用tf.expand_dims(a,0)和tf.expand_dims(b,1)具有等级2形状。 尝试以下代码:

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
c = tf.matmul(tf.expand_dims(a,0), tf.expand_dims(b, 1))
c2=tf.squeeze(c)
sess=tf.Session()
print(sess.run(c))
print(sess.run(c2))enter code here

它将显示:

[[ 91.]]
91.0