我正在浏览这两个 librosa 文档:melspectrogram和stft。
我正在研究可变长度的音频数据集,但我不太了解形状。例如:
(waveform, sample_rate) = librosa.load('audio_file')
spectrogram = librosa.feature.melspectrogram(y=waveform, sr=sample_rate)
dur = librosa.get_duration(waveform)
spectrogram = torch.from_numpy(spectrogram)
print(spectrogram.shape)
print(sample_rate)
print(dur)
Run Code Online (Sandbox Code Playgroud)
输出:
torch.Size([128, 150])
22050
3.48
Run Code Online (Sandbox Code Playgroud)
我得到的有以下几点:
我试图理解或计算:
n_fft是什么?我的意思是它到底对音频波做了什么?我在文档中读到以下内容:
n_fft : int > 0 [标量]
用零填充后加窗信号的长度。STFT 矩阵 D 的行数为 (1 + n_fft/2)。默认值 n_fft=2048 个样本,对应于 22050 Hz 采样率下的 93 毫秒物理持续时间,即 librosa 中的默认采样率。
这意味着在每个窗口中采集 2048 个样本,这意味着 --> 1/22050 * 2048 = 93[ms]。每 …
我正在做的一个项目是将文本转换为数字。(例如,“hello world”将转换为“8 5 12 12 15 27 23 15 18 12 4”)。
在我的代码的第 10 行中,for 循环导致以下错误消息:
Traceback (most recent call last):
File "C:\Users\gabri\PycharmProjects\padding\main.py", line 15, in <module>
converter(plaintext)
File "C:\Users\gabri\PycharmProjects\padding\main.py", line 10, in converter
for n in plaintext:
TypeError: 'types.GenericAlias' object is not iterable
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
alphabet = ("a","b","c","d","e","f","g","h","i","j","k","l","m",'n',"o","p","q","r",'s','t','u','v','w','x','y','z')
def getplaintext():
global plaintext
plaintext = list[input("Enter plaintext:.....")]
print(plaintext)
def converter(plaintext):
for n in plaintext:
print(n)
getplaintext()
converter(plaintext)
Run Code Online (Sandbox Code Playgroud)
有谁知道是什么导致了这个错误?
以下代码定义了一个简单的协议和一个几乎实现该协议的类。唯一的区别是该run()方法在协议中接受一个参数,但它不是以这种方式实现的。
然而,isinstance()检查返回 true,这是出乎意料的。
据我了解PEP-544这应该有效。尽管检查函数签名还不清楚。
当在成员中使用错误的数据类型(例如,在协议中将ORDER其更改为)时,也会发生同样的问题。str
我知道类型提示只是......嗯......“提示”并且在运行时不会强制执行。
但是,在我的应用程序中,确保某些类遵循定义的协议以获得更清晰的错误消息将很有用。它使用插件架构,加载插件后,如果该插件遵循所需的协议,则进行快速“健全性检查”会很有用,如果没有,则提供早期且有用的错误消息,而不是导致异常稍后在下游。
from typing_extensions import Protocol, runtime_checkable
@runtime_checkable
class PFoo(Protocol):
ORDER: int
def run(self, a: int) -> None:
...
class Hello:
ORDER = 10
def run(self) -> None:
print(1)
# Returns "True" evn though the signature of "run()" doesn't match
print(isinstance(Hello(), PFoo))
Run Code Online (Sandbox Code Playgroud) 我尝试在现有字典的第二层实例化一个空字典,然后为其分配一个键值对,但 MyPy 抛出错误。
这是一个最小的示例,当激活 MyPy 检查时它将重现它:
result = {"Test": "something"}
result['key'] = {}
result['key']['sub_key'] = ["some string", "another string"]
Run Code Online (Sandbox Code Playgroud)
这里的错误将类似于:
mypy(error): Incompatible types in assignment (expression has type
"Dict[<nothing>, <nothing>]", target has type "List[str]")
Run Code Online (Sandbox Code Playgroud)
我该如何防止这个错误?根据类似的问题,建议这样做
result['key'] = {} # type: ignore
Run Code Online (Sandbox Code Playgroud)
作为一种解决方法,但这似乎不是很优雅,这就是为什么我想知道是否还有更多的事情可以做。
考虑以下元类/类定义:
class Meta(type):
"""A python metaclass."""
def greet_user(cls):
"""Print a friendly greeting identifying the class's name."""
print(f"Hello, I'm the class '{cls.__name__}'!")
class UsesMeta(metaclass=Meta):
"""A class that uses `Meta` as its metaclass."""
Run Code Online (Sandbox Code Playgroud)
我们知道,在元类中定义一个方法意味着它被类继承,并且可以被类使用。这意味着交互式控制台中的以下代码可以正常工作:
class Meta(type):
"""A python metaclass."""
def greet_user(cls):
"""Print a friendly greeting identifying the class's name."""
print(f"Hello, I'm the class '{cls.__name__}'!")
class UsesMeta(metaclass=Meta):
"""A class that uses `Meta` as its metaclass."""
Run Code Online (Sandbox Code Playgroud)
然而,这种方法的一个主要缺点是我们可能包含在方法定义中的任何文档都丢失了。如果我们help(UsesMeta)在交互式控制台中键入,我们会看到没有对方法的引用greet_user,更不用说我们在方法定义中放入的文档字符串了:
>>> UsesMeta.greet_user()
Hello, I'm the class 'UsesMeta'!
Run Code Online (Sandbox Code Playgroud)
现在当然,__doc__类的属性是 writable …
Python 中是否有 (eg) 的简写print(f'type(var) = {type(var)}'),而不必在文本和{.}?
简短的回答可能是“不”,但我不得不问!
例如,在 SAS 中,可以使用&=将宏变量及其值输出到日志...
%let macrovar = foobar;
%put &=macrovar;
Run Code Online (Sandbox Code Playgroud)
在日志中返回: MACROVAR = foobar
这是我的第一个问题,我发现很难找到答案,所以如果有人问并回答了,我深表歉意。
我有很多具有相同签名的函数,比如(int, int) -> int.
有没有办法用 a Callable(或其他东西)来输入这些函数,以避免为每个函数指定参数类型和返回类型?我想做类似的事情(但显然失败了):
from typing import Callable
f: Callable[[int, int], int]
def f(x, y): # with the previous line, this is equivalent to 'def f(x: int, y: int) -> int:'
...
Run Code Online (Sandbox Code Playgroud)
运行 mypy 结果:
file.py:4: error: Name "f" already defined on line 3
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud) 给出如下内容:
import importlib
module_path = "mod"
mod = importlib.import_module(module_path, package=None)
print(mod.Foo.Bar.x)
Run Code Online (Sandbox Code Playgroud)
哪里mod.py:
class Foo:
class Bar:
x = 1
Run Code Online (Sandbox Code Playgroud)
mypy file.py --strict 引发以下错误:
file.py:7: error: Module has no attribute "Foo" [attr-defined]
Run Code Online (Sandbox Code Playgroud)
我想知道应该如何进行类型提示,或者这是否是通常会被忽略的东西# type: ignore[attr-defined] (假设代码是必要的,并且唯一的选项是类型提示或忽略类型提示)?
importlib在这种情况下使用使用的方式importlib是有一些路径:
x.y.<changes>.z
Run Code Online (Sandbox Code Playgroud)
哪里<changes>是动态的,其他的都是固定的。我确信该模块将包含正在调用的属性,但由于<changes>,importlib用于导入。
可以概括为:
我不确切地知道我将导入哪个模块,但我知道它将有一个
Foo类。
我正在尝试定义一个类,该类将另一个类作为属性_model并将实例化该类的对象。
from abc import ABC
from typing import Generic, TypeVar, Any, ClassVar, Type
Item = TypeVar("Item", bound=Any)
class SomeClass(Generic[Item], ABC):
_model: ClassVar[Type[Item]]
def _compose_item(self, **attrs: Any) -> Item:
return self._model(**attrs)
Run Code Online (Sandbox Code Playgroud)
self._model(**attrs)我认为返回 , 的实例应该是显而易见的Item,因为_model被显式声明为Type[Item]并被attrs声明为Dict[str, Any]。
但我从中得到的mypy 0.910是:
test.py: note: In member "_compose_item" of class "SomeClass":
test.py:11: error: Returning Any from function declared to return "Item"
return self._model(**attrs)
^
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
考虑:
course_db = Course(title='Databases')
course_db.save()
Run Code Online (Sandbox Code Playgroud)
来自 C++ 背景,我希望(course_db = Course(title='Databases'))表现得像 C++ 中的那样,即分配Course(title='Databases')并course_db 返回分配的对象,以便我可以将其用作更大表达式的一部分。例如,我希望以下代码与上面的代码执行相同的操作:
(course_db = Course(title='Databases')).save()
Run Code Online (Sandbox Code Playgroud)
这一假设得到了一些使用“Python 中的赋值运算符”等术语的快速 Google 搜索的支持,例如这篇文章。但是当我尝试这个时,我遇到了语法错误。
为什么我不能在 Python 中执行此操作,我可以做什么?
python ×10
type-hinting ×5
mypy ×4
audio ×1
class-method ×1
docstring ×1
f-string ×1
librosa ×1
metaclass ×1
python-3.x ×1
sas ×1
spectrogram ×1
typeerror ×1