我已经将一个Matlab函数转换为Python语言,用它来创建一个过完备的离散余弦变换矩阵,用它来表示向量空间中的一维信号。
function D = odctdict(n,L)
%ODCTDICT Overcomplete DCT dictionary.
% D = ODCTDICT(N,L) returns the overcomplete DCT dictionary of size NxL
% for signals of length N.
%
% See also ODCT2DICT, ODCT3DICT, ODCTNDICT.
D = zeros(n,L);
D(:,1) = 1/sqrt(n);
for k = 2:L
v = cos((0:n-1)*pi*(k-1)/L)';
v = v-mean(v);
D(:,k) = v/norm(v);
end
import numpy as np
def odct1dict(n, l):
"""
1-D Overcomplete DCT dictionary.
D = odct1dict(N, L) returns the overcomplete DCT dictionary of size NxL
for signals of length N.
:param n: signal size
:type n: int
:param l: number of atoms
:type l: int
:return: 1-D Overcomplete DCT dictionary NumPy array
"""
d = np.zeros((n, l))
d[:, 0] = 1 / np.sqrt(n)
for k in range(1, l):
v = np.transpose(np.cos(np.arange(0, n) * np.pi * k * l))
v = v - np.mean(v)
d[:, k] = v / np.linalg.norm(v)
return d
我使用PyCharm作为Python IDE,这个软件在for循环内的指令v = np.transpose(np.cos(np.arange(0, n) * np.pi * k * l))
中发出了一个警告,我不理解这个警告,特别是对于np.transpose
函数的参数np.cos(np.arange(0, n) * np.pi * k * l)
。
Expected type 'Union[ndarray, Iterable]', got 'int' instead less...
This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations.
你能给我解释一下这个警告吗?如何纠正呢?写这种指令的正确方法是什么?
这些误报在PyCharm的numpy代码中经常发生。在thread discussing this issue with JetBrains support中,他们说:
对于自己函数的参数,可以write docstrings to let PyCharm know what type to expect。但是对于很多numpy代码来说,这并不相关。我发现了两种解决方案:
# noinspection PyTypeChecker
行抑制每行或每个函数的警告。有关抑制警告的详细信息,请参见official guide在this answer中使用type hinting:
在buzjwa的回答后面加上:
选项3:使用mypy进行类型检查,并手动添加为numpy创建的第三方存根文件here
您需要将这个存根文件添加到您的内部python类型中。告诉我们你过得怎么样!
我猜PyCharm并不完全理解numpy。它看起来和行为都像有效的Python:
使用我的IDE,
Ipython
,我可以:相关问题 更多 >
编程相关推荐