Litchi1999 发表于 2023-9-16 17:54:30

要怎么加上if name == 'main':这一句呢

源码:
import torch
import torch.nn as nn
from metric import get_stoi, get_pesq
from scipy.io import wavfile
import numpy as np
from checkpoints import Checkpoint
from torch.utils.data import DataLoader
from helper_funcs import snr, numParams
from eval_composite import eval_composite
from AudioData import EvalDataset, EvalCollate
from new_model import Net
import h5py
import os

os.environ['CUDA_VISIBLE_DEVICES'] = '0'

sr = 16000

#file_name = 'psquare_17.5'
#test_file_list_path = '/media/concordia/DATA/KaiWang/pytorch_learn/pytorch_for_speech/voice_bank/Transformer/v5/test_file_break' + '/' + file_name
#audio_file_save = 'D:/pycharmProject/TSTNN-master/Mydataset/enhanced_audio' + '/' + 'enhanced_' + file_name

test_file_list_path = "D:/pycharmProject/TSTNN-master/test_file_list"
audio_file_save = "D:/pycharmProject/TSTNN-master/Mydataset/enhanced_audio/"

if not os.path.isdir(audio_file_save):
    os.makedirs(audio_file_save)

with open(test_file_list_path, 'r') as test_file_list:
    file_list =
#audio_name = os.path.basename(file_list)

print(file_list)


test_data = EvalDataset(test_file_list_path, frame_size=512, frame_shift=256)
test_loader = DataLoader(test_data,
                               batch_size=1,
                               shuffle=False,
                               num_workers=4,
                               collate_fn=EvalCollate())

ckpt_path = 'D:/pycharmProject/TSTNN-master/checkpoints/best.model'

model = Net()
model = nn.DataParallel(model, device_ids=)
checkpoint = Checkpoint()
checkpoint.load(ckpt_path)
model.load_state_dict(checkpoint.state_dict)
model.cuda()
print(checkpoint.start_epoch)
print(checkpoint.best_val_loss)
print(numParams(model))


# test function
def evaluate(net, eval_loader):
    net.eval()

    print('********Starting metrics evaluation on test dataset**********')
    total_stoi = 0.0
    total_ssnr = 0.0
    total_pesq = 0.0
    total_csig = 0.0
    total_cbak = 0.0
    total_covl = 0.0

    with torch.no_grad():
      count, total_eval_loss = 0, 0.0
      for k, (features, labels) in enumerate(eval_loader):
            features = features.cuda()#
            labels = labels.cuda()#

            output = net(features)#
            output = output.squeeze()#

            # keep length same (output label)
            output = output[:labels.shape[-1]]

            eval_loss = torch.mean((output - labels) ** 2)
            total_eval_loss += eval_loss.data.item()

            est_sp = output.cpu().numpy()
            cln_raw = labels.cpu().numpy()

            eval_metric = eval_composite(cln_raw, est_sp, sr)

            #st = get_stoi(cln_raw, est_sp, sr)
            #pe = get_pesq(cln_raw, est_sp, sr)
            #sn = snr(cln_raw, est_sp)
            total_pesq += eval_metric['pesq']
            total_ssnr += eval_metric['ssnr']
            total_stoi += eval_metric['stoi']
            total_cbak += eval_metric['cbak']
            total_csig += eval_metric['csig']
            total_covl += eval_metric['covl']

            wavfile.write(os.path.join(audio_file_save, os.path.basename(file_list)), sr, est_sp.astype(np.float32))

            count += 1
      avg_eval_loss = total_eval_loss / count

    return avg_eval_loss, total_stoi / count, total_pesq / count, total_ssnr / count, total_csig / count, total_cbak / count, total_covl / count


def eva_noisy(file_path):
    print('********Starting metrics evaluation on raw noisy data**********')
    total_stoi = 0.0
    total_ssnr = 0.0
    total_pesq = 0.0
    total_csig = 0.0
    total_cbak = 0.0
    total_covl = 0.0
    count = 0
   

    with open(file_path, 'r') as eva_file_list:
      file_list =


    for i in range(len(file_list)):
      filename = file_list
      reader = h5py.File(filename, 'r')

      noisy_raw = reader['noisy_raw'][:]
      cln_raw = reader['clean_raw'][:]

      eval_metric = eval_composite(cln_raw, noisy_raw, sr)

      total_pesq += eval_metric['pesq']
      total_ssnr += eval_metric['ssnr']
      total_stoi += eval_metric['stoi']
      total_cbak += eval_metric['cbak']
      total_csig += eval_metric['csig']
      total_covl += eval_metric['covl']

      count += 1

    return total_stoi / count, total_pesq / count, total_ssnr / count, total_cbak / count, total_csig / count, total_covl / count


avg_eval, avg_stoi, avg_pesq, avg_ssnr, avg_csig, avg_cbak, avg_covl = evaluate(model, test_loader)

#avg_stoi, avg_pesq, avg_ssnr, avg_cbak, avg_csig, avg_covl = eva_noisy(test_file_list_path)

#print('Avg_loss: {:.4f}'.format(avg_eval))
print('STOI: {:.4f}'.format(avg_stoi))
print('SSNR: {:.4f}'.format(avg_ssnr))
print('PESQ: {:.4f}'.format(avg_pesq))
print('CSIG: {:.4f}'.format(avg_csig))
print('CBAK: {:.4f}'.format(avg_cbak))
print('COVL: {:.4f}'.format(avg_covl))


isdkz 发表于 2023-9-16 17:54:36

可以在代码的最后加上if name == 'main':这一句,如下所示:

if __name__ == '__main__':
    avg_eval, avg_stoi, avg_pesq, avg_ssnr, avg_csig, avg_cbak, avg_covl = evaluate(model, test_loader)
    print('STOI: {:.4f}'.format(avg_stoi))
    print('SSNR: {:.4f}'.format(avg_ssnr))
    print('PESQ: {:.4f}'.format(avg_pesq))
    print('CSIG: {:.4f}'.format(avg_csig))
    print('CBAK: {:.4f}'.format(avg_cbak))
    print('COVL: {:.4f}'.format(avg_covl))

这样做的目的是,当直接运行该文件时,if name == 'main':以下的代码块将会被执行,而当该文件被作为模块导入时,if name == 'main':以下的代码块则不会被执行。

Litchi1999 发表于 2023-9-16 17:55:24

报错信息如下
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
File "D:\Anaconda3\envs\torchGPU\lib\runpy.py", line 288, in run_path
    return _run_module_code(code, init_globals, run_name,
File "D:\Anaconda3\envs\torchGPU\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
File "D:\Anaconda3\envs\torchGPU\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
File "D:\pycharmProject\TSTNN-master\test.py", line 142, in <module>
    avg_eval, avg_stoi, avg_pesq, avg_ssnr, avg_csig, avg_cbak, avg_covl = evaluate(model, test_loader)
File "D:\pycharmProject\TSTNN-master\test.py", line 70, in evaluate
    for k, (features, labels) in enumerate(eval_loader):
File "D:\Anaconda3\envs\torchGPU\lib\site-packages\torch\utils\data\dataloader.py", line 441, in __iter__
    return self._get_iterator()
File "D:\Anaconda3\envs\torchGPU\lib\site-packages\torch\utils\data\dataloader.py", line 388, in _get_iterator
    return _MultiProcessingDataLoaderIter(self)
File "D:\Anaconda3\envs\torchGPU\lib\site-packages\torch\utils\data\dataloader.py", line 1042, in __init__
    w.start()
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\context.py", line 327, in _Popen
    return Popen(process_obj)
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
File "D:\Anaconda3\envs\torchGPU\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RuntimeError('''
RuntimeError:
      An attempt has been made to start a new process before the
      current process has finished its bootstrapping phase.

      This probably means that you are not using fork to start your
      child processes and you have forgotten to use the proper idiom
      in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

      The "freeze_support()" line can be omitted if the program
      is not going to be frozen to produce an executable.

Litchi1999 发表于 2023-9-16 18:15:30

isdkz 发表于 2023-9-16 17:54
可以在代码的最后加上if name == 'main':这一句,如下所示:

if __name__ == '__main__':


感谢!没有错误但有个警告
RuntimeWarning: invalid value encountered in scalar divide
rcoeff = (R - sum_term) / E
页: [1]
查看完整版本: 要怎么加上if name == 'main':这一句呢