简体   繁体   English

Cython:矩阵乘法

[英]Cython: matrix multiplication

I have cythonized the following file that uses numpy's matrix multiplication:我已经对以下使用 numpy 的矩阵乘法的文件进行了 cythonized:

def cell(float[:, ::1] a, float[:, ::1] b):
  c = a @ b
  return c

However, when I call it with:但是,当我用以下方式调用它时:

from matmul import cell
import numpy as np


a = np.zeros((1, 64), dtype=np.float32)
b = np.zeros((64, 64), dtype=np.float32)
c = cell(a, b)

I get the following error:我收到以下错误:

TypeError: unsupported operand type(s) for @: _memoryviewslice and _memoryviewslice类型错误:@ 不支持的操作数类型:_memoryviewslice 和 _memoryviewslice

How can I perform matrix multiplication with Cython?如何使用 Cython 执行矩阵乘法?

Context: the function "cell" is part of a code I wrote that performs a prediction by an LSTM network (I wrote it manually, without using PyTorch or Tensorflow, just NumPy).上下文:function“单元”是我编写的代码的一部分,它通过 LSTM 网络执行预测(我手动编写了它,没有使用 PyTorch 或 Tensorflow)。 I need to speed up the code to be able to use the network in real-time.我需要加速代码才能实时使用网络。

If that's all you're doing there's literally no point in adding the types for the argument of cell - all you're doing is adding expensive type-checks for no reason.如果这就是你所做的一切,那么为cell的参数添加类型实际上是没有意义的——你所做的只是无缘无故地添加昂贵的类型检查。 Cython can't make useful use of these types. Cython 无法有效利用这些类型。 Just leave a and b untyped.只需不ab即可。

If you do actually need to fix memoryviews operations with Numpy whole-array operations the easiest solution is to call np.asarray如果您确实需要使用 Numpy 整个数组操作来修复 memoryviews 操作,最简单的解决方案是调用np.asarray

def cell(float[:, ::1] a, float[:, ::1] b):
  c = np.asarray(a) @ np.asarray(b)
  return c

You aren't getting any benefit from Cython here - it's just calling into the Numpy matrix multiply code.您在这里没有从 Cython 获得任何好处 - 它只是调用 Numpy 矩阵乘法代码。 So only do this where you need to mix it with some operations where you do benefit from Cython.因此,仅在需要将其与您确实受益于 Cython 的某些操作混合时才执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM