Skip to content

Instantly share code, notes, and snippets.

@tam17aki
Last active December 16, 2022 08:56
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tam17aki/b60313df3f438bad80e77cc1055bd311 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""Training script for Sinusoidal Frequency Estimation by Gradient Descent.
Copyright (C) 2022 by Akira TAMAMORI
Copyright (C) 2022 by @xiao_ming
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import librosa
import matplotlib.pyplot as plt
import numpy as np
import torch
from hydra import compose, initialize
from progressbar import progressbar
from torch import nn
class SFE(nn.Module):
"""Sinusoidal Frequency Estimation (SFE) class."""
def __init__(self, cfg, device):
"""Initialize class."""
super().__init__()
n_sines = cfg.model.n_sines
init_freq = torch.rand(n_sines, 1) * torch.pi
init_phase = torch.rand(n_sines, 1) * torch.pi
self._omega = nn.Parameter(torch.exp(init_freq * 1.0j))
self._phi = nn.Parameter(torch.exp(init_phase * 1.0j))
self.n_sines = n_sines
self.arr_n = torch.arange(cfg.feature.frame_length).to(device)
self.criterion = nn.MSELoss()
self.config = cfg
def forward(self):
"""Perform forward propagation."""
mag = self._omega.abs().pow(self.arr_n) * self._phi.abs()
sinusoid = torch.cos(self._omega.angle() * self.arr_n + self._phi.angle())
estimated = mag * sinusoid
estimated = torch.sum(estimated, dim=0)
return estimated
def get_loss(self, target):
"""Return MSE loss."""
estimated_sinusoid = self.forward()
loss = self.criterion(estimated_sinusoid, target)
return loss
def get_f0(self):
"""Return fundamental frequency in Hz."""
freq = self._omega[:].angle() * self.config.feature.sample_rate / (2 * np.pi)
freq = freq.to("cpu").detach().numpy().copy() # tensor to numpy
return np.min(np.abs(freq))
@property
def omega(self):
"""Get omega."""
return self._omega
@property
def phi(self):
"""Get phi."""
return self._phi
def get_power_max_frame(audio, frame_length, hop_length):
"""Extract the frame with maximum power."""
frames = librosa.util.frame(
audio, frame_length=frame_length, hop_length=hop_length
).T
max_ind = np.argmax(np.sum(frames * frames, axis=1))
max_frame = frames[max_ind, :]
max_frame = max_frame / np.abs(np.max(max_frame)) # normalise within [-1, 1]
return max_frame
def plot_waveform(audio, estimated, model, train_loss, cfg):
"""Extract the frame with maximum power."""
sample_rate = cfg.feature.sample_rate
fig = plt.figure(figsize=(cfg.demo.figsize.width, cfg.demo.figsize.height))
time = np.arange(len(audio)) / sample_rate
axes = fig.add_subplot(1, 1, 1)
axes.plot(time, audio, label="original")
axes.plot(time, estimated, label="estimated")
axes.set_xlabel("Time (sec)", fontsize=cfg.demo.fontsize)
axes.set_ylabel("Amplitude", fontsize=cfg.demo.fontsize)
axes.set_title(f"Loss = {train_loss:.6f}", fontsize=cfg.demo.fontsize)
axes.tick_params(axis="x", labelsize=cfg.demo.fontsize)
axes.tick_params(axis="y", labelsize=cfg.demo.fontsize)
axes.legend(fontsize=14)
plt.savefig(cfg.demo.out_image)
plt.show()
def training_loop(target, model, cfg):
"""Perform training loop."""
optimizer = torch.optim.Adam(
[model.omega, model.phi], lr=cfg.training.learning_rate
)
train_loss = 0.0
for _ in progressbar(range(1, cfg.training.n_epochs)):
optimizer.zero_grad()
loss = model.get_loss(target)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_loss /= cfg.training.n_epochs
print(f"Loss: {train_loss}")
return train_loss
def main(wav_file, cfg):
"""Perform model training."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# load target waveform
wav_file = os.path.join(os.path.join(cfg.SFE.root_dir, cfg.SFE.data_dir), wav_file)
audio, _ = librosa.load(wav_file, sr=cfg.feature.sample_rate)
max_frame = get_power_max_frame(
audio, cfg.feature.frame_length, cfg.feature.hop_length
)
target = torch.from_numpy(max_frame.astype(np.float32)).clone() # numpy to tensor
target = target.to(device)
# instantiate model for training
model = SFE(cfg, device).to(device)
# perform training loop
train_loss = training_loop(target, model, cfg)
# plot estimated sinusoid wave
estimated = model.forward()
estimated = estimated.to("cpu").detach().numpy().copy()
plot_waveform(max_frame, estimated, model, train_loss, cfg)
if __name__ == "__main__":
with initialize(version_base=None, config_path="."):
config = compose(config_name="config")
main(config.demo.in_wav, config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment