Numpy:我可以在没有einsum的情况下进行张量Hadamard乘法吗?

时间:2016-07-18 18:31:27

标签: python numpy

我有一个等级四张量A(比如指数(a,b,i,j))和等级二张量B(比如指数(i,j))我想计算一种Hadamard乘法他们

也就是说,如果我们调用产品C,我想要 // Container let barViewFrame = CGRectMake(0, 0, view.frame.width, 44) let barViewContainer = UIView(frame: barViewFrame) barViewContainer.backgroundColor = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1.0) tableView.tableHeaderView = barViewContainer // Edit Button let editButton = UIButton(type: .System) editButton.bounds = CGRectMake(0, 0, 44, 44) editButton.setTitle("Edit", forState: .Normal) // Search Bar let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 50, height: 44)) searchBar.placeholder = "Search" searchBar.searchBarStyle = .Prominent searchBar.barTintColor = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1.0) // Sort Button let sortButtton = UIButton(type: .Custom) sortButtton.bounds = CGRectMake(0, 0, 44, 44) sortButtton.setImage(UIImage(named: "Sort"), forState: .Normal) // Stackview let stackViewH = UIStackView(arrangedSubviews: [editButton, searchBar, sortButtton]) stackViewH.axis = .Horizontal stackViewH.alignment = .Center stackViewH.spacing = 8 barViewContainer.addSubview(stackViewH) barViewContainer.addConstraints([ stackViewH.leftAnchor.constraintEqualToAnchor(barViewContainer.leftAnchor), stackViewH.topAnchor.constraintEqualToAnchor(barViewContainer.topAnchor), stackViewH.rightAnchor.constraintEqualToAnchor(barViewContainer.rightAnchor), stackViewH.bottomAnchor.constraintEqualToAnchor(barViewContainer.bottomAnchor)]) 。使用C[a,b,i,j] == A[a,b,i,j] * B[i,j]有一种相当简单的方法可以做到这一点但是我被告知使用einsumeinsum等方法相比有显着的性能影响,但我找不到从文档中避免它的好方法。

我可能错过了它;我是新手,而不是numpy的专家。

1 个答案:

答案 0 :(得分:4)

C = A * B

broadcasting rules之后,NumPy将从最后一个轴开始排列AB的形状:

A: (a, b, i, j)
B:       (i, j)

并将AB的相应元素相乘以创建C

   A[a, b, i, j]
*  B[      i, j]
== C[a, b, i, j]