options.py 13.6 KB
Newer Older
HypoX64's avatar
HypoX64 已提交
1 2
import argparse
import os
3
import time
H
hypox64 已提交
4
import numpy as np
H
HypoX64 已提交
5 6 7 8 9
from . import util,dsp,plot

import sys
sys.path.append("..")
from data import statistics
H
hypox64 已提交
10

HypoX64's avatar
HypoX64 已提交
11 12 13 14 15 16
class Options():
    def __init__(self):
        self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        self.initialized = False

    def initialize(self):
H
hypox64 已提交
17
        # ------------------------Base------------------------
18
        self.parser.add_argument('--gpu_id', type=int, default=0,help='choose which gpu want to use, 0 | 1 | 2 ...')        
H
hypox64 已提交
19
        self.parser.add_argument('--no_cudnn', action='store_true', help='if specified, do not use cudnn')
H
hypox64 已提交
20 21
        self.parser.add_argument('--label', type=str, default='auto',help='number of labels')
        self.parser.add_argument('--input_nc', type=str, default='auto', help='of input channels')
H
hypox64 已提交
22
        self.parser.add_argument('--loadsize', type=str, default='auto', help='load data in this size')
H
hypox64 已提交
23
        self.parser.add_argument('--finesize', type=str, default='auto', help='crop your data into this size')
H
hypox64 已提交
24
        self.parser.add_argument('--label_name', type=str, default='auto',help='name of labels,example:"a,b,c,d,e,f"')
H
hypox64 已提交
25
        
H
HypoX64 已提交
26
        # ------------------------Preprocessing------------------------
H
hypox64 已提交
27
        self.parser.add_argument('--normliaze', type=str, default='5_95', help='mode of normliaze, 5_95 | maxmin | None')      
H
HypoX64 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
        # filter
        self.parser.add_argument('--filter', type=str, default='None', help='type of filter, fft | fir | iir |None')
        self.parser.add_argument('--filter_mod', type=str, default='bandpass', help='mode of fft_filter, bandpass | bandstop')
        self.parser.add_argument('--filter_fs', type=int, default=1000, help='fs of filter')
        self.parser.add_argument('--filter_fc', type=str, default='[]', help='fc of filter, eg. [0.1,10]')

        # filter by wavelet
        self.parser.add_argument('--wave', type=str, default='None', help='wavelet name string, wavelet(eg. dbN symN haar gaus mexh) | None')
        self.parser.add_argument('--wave_level', type=int, default=5, help='decomposition level')
        self.parser.add_argument('--wave_usedcoeffs', type=str, default='[]', help='Coeff used for reconstruction, \
            eg. when level = 6 usedcoeffs=[1,1,0,0,0,0,0] : reconstruct signal with cA6, cD6')
        self.parser.add_argument('--wave_channel', action='store_true', help='if specified, input reconstruct each coeff as a channel.')
        
        
        # ------------------------Data Augmentation------------------------
        # base
H
HypoX64 已提交
44 45 46
        self.parser.add_argument('--augment', type=str, default='scale', 
            help='all | scale,warp,app,aaft,iaaft,filp,spike,step,slope,white,pink,blue,brown,violet , enter some of them')
        self.parser.add_argument('--augment_noise_lambda', type=float, default = 0.1, help='noise level(spike,step,slope,white,pink,blue,brown,violet)')
H
HypoX64 已提交
47 48
        # fft channel --> use fft to improve frequency domain information.
        self.parser.add_argument('--augment_fft', action='store_true', help='if specified, use fft to improve frequency domain informationa')
H
HypoX64 已提交
49 50
        
        # self.parser.add_argument('--augment_times', type=float, default=10, help='how many times that will be augmented')
H
HypoX64 已提交
51 52 53 54 55 56 57 58 59 60 61

        # for gan,it only support when fold_index = 1 or 0 now
        # only support when k_fold =0 or 1
        self.parser.add_argument('--gan', action='store_true', help='if specified, using gan to augmente dataset')
        self.parser.add_argument('--gan_lr', type=float, default=0.0002,help='learning rate')
        self.parser.add_argument('--gan_augment_times', type=float, default=2,help='how many times that will be augmented by dcgan')
        self.parser.add_argument('--gan_latent_dim', type=int, default=100,help='dimensionality of the latent space')
        self.parser.add_argument('--gan_labels', type=str, default='[]',help='which label that will be augmented by dcgan, eg: [0,1,2,3]')
        self.parser.add_argument('--gan_epochs', type=int, default=100,help='number of epochs of gan training')

        # ------------------------Dataset------------------------
H
hypox64 已提交
62
        """--fold_index
H
HypoX64 已提交
63
        When --k_fold != 0 or 1:
H
hypox64 已提交
64 65 66 67 68
        Cut dataset into sub-set using index , and then run k-fold with sub-set
        If input 'auto', it will shuffle dataset and then cut dataset equally
        If input: [2,4,6,7]
        when len(dataset) == 10
        sub-set: dataset[0:2],dataset[2:4],dataset[4:6],dataset[6:7],dataset[7:]
H
HypoX64 已提交
69
        -------
H
HypoX64 已提交
70
        When --k_fold == 0 or 1:
H
hypox64 已提交
71 72 73 74 75
        If input 'auto', it will shuffle dataset and then cut 80% dataset to train and other to eval
        If input: [5]
        when len(dataset) == 10
        train-set : dataset[0:5]  eval-set : dataset[5:]
        """
H
HypoX64 已提交
76
        self.parser.add_argument('--k_fold', type=int, default=0,help='fold_num of k-fold.If 0 or 1, no k-fold and cut 80% to train and other to eval')
H
hypox64 已提交
77 78
        self.parser.add_argument('--fold_index', type=str, default='auto',
            help='where to fold, eg. when 5-fold and input: [2,4,6,7] -> sub-set: dataset[0:2],dataset[2:4],dataset[4:6],dataset[6:7],dataset[7:]')
H
HypoX64 已提交
79 80 81
        self.parser.add_argument('--dataset_dir', type=str, default='./datasets/simple_test',help='your dataset path')
        self.parser.add_argument('--save_dir', type=str, default='./checkpoints/',help='save checkpoints')
        self.parser.add_argument('--load_thread', type=int, default=8,help='how many threads when load data')  
H
hypox64 已提交
82 83 84 85
        self.parser.add_argument('--mergelabel', type=str, default='None',
            help='merge some labels to one label and give the result, example:"[[0,1,4],[2,3,5]]" -> label(0,1,4) regard as 0,label(2,3,5) regard as 1')
        self.parser.add_argument('--mergelabel_name', type=str, default='None',help='name of labels,example:"a,b,c,d,e,f"')
        
H
hypox64 已提交
86 87 88
        # ------------------------Network------------------------
        """Available Network
        1d: lstm, cnn_1d, resnet18_1d, resnet34_1d, multi_scale_resnet_1d,
H
Add mlp  
HypoX64 已提交
89
            micro_multi_scale_resnet_1d,autoencoder,mlp
H
hypox64 已提交
90
        2d: mobilenet, dfcnn, multi_scale_resnet, resnet18, resnet50, resnet101,
H
hypox64 已提交
91 92 93 94 95 96 97 98
            densenet121, densenet201, squeezenet
        """
        self.parser.add_argument('--model_name', type=str, default='micro_multi_scale_resnet_1d',help='Choose model  lstm...')
        self.parser.add_argument('--model_type', type=str, default='auto',help='1d | 2d')
        # For lstm 
        self.parser.add_argument('--lstm_inputsize', type=str, default='auto',help='lstm_inputsize of LSTM')
        self.parser.add_argument('--lstm_timestep', type=int, default=100,help='time_step of LSTM')
        # For autoecoder
H
hypox64 已提交
99
        self.parser.add_argument('--feature', type=int, default=3, help='number of encoder features')
H
hypox64 已提交
100
        # For 2d network(stft spectrum)
H
hypox64 已提交
101
        # Please cheek ./save_dir/spectrum_eg.jpg to change the following parameters
H
hypox64 已提交
102 103
        self.parser.add_argument('--stft_size', type=int, default=512, help='length of each fft segment')
        self.parser.add_argument('--stft_stride', type=int, default=128, help='stride of each fft segment')
H
hypox64 已提交
104
        self.parser.add_argument('--stft_n_downsample', type=int, default=1, help='downsample befor stft')
H
hypox64 已提交
105
        self.parser.add_argument('--stft_no_log', action='store_true', help='if specified, do not log1p spectrum')
H
hypox64 已提交
106 107
        self.parser.add_argument('--stft_shape', type=str, default='auto', help='shape of stft. It depend on \
            stft_size,stft_stride,stft_n_downsample. Do not input this parameter.')
H
hypox64 已提交
108 109

        # ------------------------Training Matters------------------------
H
hypox64 已提交
110
        self.parser.add_argument('--pretrained', type=str, default='',help='pretrained model path. If not specified, fo not use pretrained model')
H
hypox64 已提交
111
        self.parser.add_argument('--continue_train', action='store_true', help='if specified, continue train')
H
hypox64 已提交
112
        self.parser.add_argument('--lr', type=float, default=0.001,help='learning rate') 
H
hypox64 已提交
113
        self.parser.add_argument('--batchsize', type=int, default=64,help='batchsize')
H
hypox64 已提交
114
        self.parser.add_argument('--weight_mod', type=str, default='auto',help='Choose weight mode: auto | normal')
H
hypox64 已提交
115
        self.parser.add_argument('--epochs', type=int, default=20,help='end epoch')
HypoX64's avatar
HypoX64 已提交
116
        self.parser.add_argument('--network_save_freq', type=int, default=5,help='the freq to save network')
H
hypox64 已提交
117

HypoX64's avatar
HypoX64 已提交
118 119 120 121 122 123
        self.initialized = True

    def getparse(self):
        if not self.initialized:
            self.initialize()
        self.opt = self.parser.parse_args()
HypoX64's avatar
HypoX64 已提交
124

H
hypox64 已提交
125 126 127
        if self.opt.gpu_id != -1:
            os.environ["CUDA_VISIBLE_DEVICES"] = str(self.opt.gpu_id)

H
hypox64 已提交
128
        if self.opt.label != 'auto':
H
hypox64 已提交
129 130 131
            self.opt.label = int(self.opt.label)
        if self.opt.input_nc !='auto':
            self.opt.input_nc = int(self.opt.input_nc)
H
hypox64 已提交
132 133
        if self.opt.loadsize !='auto':
            self.opt.loadsize = int(self.opt.loadsize)
H
hypox64 已提交
134 135
        if self.opt.finesize !='auto':
            self.opt.finesize = int(self.opt.finesize)
H
hypox64 已提交
136 137 138 139 140
        if self.opt.lstm_inputsize != 'auto':
            self.opt.lstm_inputsize = int(self.opt.lstm_inputsize)

        if self.opt.model_type == 'auto':
            if self.opt.model_name in ['lstm', 'cnn_1d', 'resnet18_1d', 'resnet34_1d', 
H
Add mlp  
HypoX64 已提交
141
                'multi_scale_resnet_1d','micro_multi_scale_resnet_1d','autoencoder','mlp']:
H
hypox64 已提交
142 143
                self.opt.model_type = '1d'
            elif self.opt.model_name in ['dfcnn', 'multi_scale_resnet', 'resnet18', 'resnet50',
H
hypox64 已提交
144
                'resnet101','densenet121', 'densenet201', 'squeezenet', 'mobilenet']:
H
hypox64 已提交
145 146 147 148
                self.opt.model_type = '2d'
            else:
                print('\033[1;31m'+'Error: do not support this network '+self.opt.model_name+'\033[0m')
                exit(0)
149

H
hypox64 已提交
150 151 152
        if self.opt.k_fold == 0 :
            self.opt.k_fold = 1

H
hypox64 已提交
153 154 155 156 157
        if self.opt.fold_index != 'auto':
            self.opt.fold_index = eval(self.opt.fold_index)

        if os.path.isfile(os.path.join(self.opt.dataset_dir,'index.npy')):
            self.opt.fold_index = (np.load(os.path.join(self.opt.dataset_dir,'index.npy'))).tolist()
H
hypox64 已提交
158

H
HypoX64 已提交
159
        if self.opt.augment == 'all':
H
HypoX64 已提交
160
            self.opt.augment = ['scale','warp','spike','step','slope','white','pink','blue','brown','violet','app','aaft','iaaft','filp']
H
HypoX64 已提交
161 162 163 164 165 166 167
        else:
            self.opt.augment = str2list(self.opt.augment)

        self.opt.filter_fc = eval(self.opt.filter_fc)
        self.opt.wave_usedcoeffs = eval(self.opt.wave_usedcoeffs)
        self.opt.gan_labels = eval(self.opt.gan_labels)

168
        self.opt.mergelabel = eval(self.opt.mergelabel)
H
hypox64 已提交
169 170 171
        if self.opt.mergelabel_name != 'None':
            self.opt.mergelabel_name = self.opt.mergelabel_name.replace(" ", "").split(",")

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        """Print and save options
        It will print both current options and default values(if different).
        It will save options into a text file / [checkpoints_dir] / opt.txt
        """
        message = ''
        message += '----------------- Options ---------------\n'
        for k, v in sorted(vars(self.opt).items()):
            comment = ''
            default = self.parser.get_default(k)
            if v != default:
                comment = '\t[default: %s]' % str(default)
            message += '{:>20}: {:<30}{}\n'.format(str(k), str(v), comment)
        message += '----------------- End -------------------'
        localtime = time.asctime(time.localtime(time.time()))
        util.makedirs(self.opt.save_dir)
        util.writelog(str(localtime)+'\n'+message, self.opt,True)

        return self.opt
H
hypox64 已提交
190

H
HypoX64 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
def str2list(string,out_type = 'string'):
    out_list = []
    string = string.replace(' ','').replace('[','').replace(']','')
    strings = string.split(',')
    for string in strings:
        if out_type == 'string':
            out_list.append(string)
        elif out_type == 'int':
            out_list.append(int(string))
        elif out_type == 'float':
            out_list.append(float(string))
    return out_list


def get_auto_options(opt,signals,labels):
H
hypox64 已提交
206
    
H
hypox64 已提交
207
    shape = signals.shape
H
HypoX64 已提交
208
    label_cnt,label_cnt_per,label_num = statistics.label_statistics(labels)
H
hypox64 已提交
209 210 211 212
    if opt.label =='auto':
        opt.label = label_num
    if opt.input_nc =='auto':
        opt.input_nc = shape[1]
H
hypox64 已提交
213 214
    if opt.loadsize =='auto':
        opt.loadsize = shape[2]
H
hypox64 已提交
215 216
    if opt.finesize =='auto':
        opt.finesize = int(shape[2]*0.9)
H
hypox64 已提交
217 218
    if opt.lstm_inputsize =='auto':
        opt.lstm_inputsize = opt.finesize//opt.lstm_timestep
H
hypox64 已提交
219 220 221 222 223 224 225

    # weight
    opt.weight = np.ones(opt.label)
    if opt.weight_mod == 'auto':
        opt.weight = 1/label_cnt_per
        opt.weight = opt.weight/np.min(opt.weight)
    util.writelog('Loss_weight:'+str(opt.weight),opt,True)
H
hypox64 已提交
226
    import torch
H
hypox64 已提交
227 228 229 230 231 232
    opt.weight = torch.from_numpy(opt.weight).float()
    if opt.gpu_id != -1:      
        opt.weight = opt.weight.cuda()

    # label name
    if opt.label_name == 'auto':
H
hypox64 已提交
233 234 235 236
        names = []
        for i in range(opt.label):
            names.append(str(i))
        opt.label_name = names
H
hypox64 已提交
237
    elif not isinstance(opt.label_name,list):
H
hypox64 已提交
238
        opt.label_name = opt.label_name.replace(" ", "").split(",")
H
hypox64 已提交
239 240 241

    # check stft spectrum
    if opt.model_type =='2d':
H
hypox64 已提交
242 243 244 245 246 247 248 249 250 251
        spectrums = []
        data = signals[np.random.randint(0,shape[0]-1)]
        for i in range(shape[1]):
            spectrums.append(dsp.signal2spectrum(data[i],opt.stft_size, opt.stft_stride, opt.stft_n_downsample, not opt.stft_no_log))
        plot.draw_spectrums(spectrums,opt)
        opt.stft_shape = spectrums[0].shape
        h,w = opt.stft_shape
        print('Shape of stft spectrum h,w:',opt.stft_shape)
        print('\033[1;37m'+'Please cheek ./save_dir/spectrum_eg.jpg to change parameters'+'\033[0m')
        
H
hypox64 已提交
252 253 254 255 256
        if h<64 or w<64:
            print('\033[1;33m'+'Warning: spectrum is too small'+'\033[0m') 
        if h>512 or w>512:
            print('\033[1;33m'+'Warning: spectrum is too large'+'\033[0m')

H
hypox64 已提交
257
    return opt