Exemplo n.º 1
0
    def run(self):
        # load data
        args_dict = self._default_configs()
        args = dotdict(args_dict)
        batchedData, maxTimeSteps, totalN = self.load_data(args,
                                                           mode=mode,
                                                           type=level)
        model = model_fn(args, maxTimeSteps)

        # count the num of params
        num_params = count_params(model, mode='trainable')
        all_num_params = count_params(model, mode='all')
        model.config['trainable params'] = num_params
        model.config['all params'] = all_num_params
        print(model.config)

        with tf.Session(graph=model.graph) as sess:
            # restore from stored model
            if keep == True:
                ckpt = tf.train.get_checkpoint_state(savedir)
                if ckpt and ckpt.model_checkpoint_path:
                    model.saver.restore(sess, ckpt.model_checkpoint_path)
                    print('Model restored from:' + savedir)
            else:
                print('Initializing')
                sess.run(model.initial_op)

            for epoch in range(num_epochs):
                ## training
                start = time.time()
                if mode == 'train':
                    print('Epoch', epoch + 1, '...')
                batchErrors = np.zeros(len(batchedData))
                batchRandIxs = np.random.permutation(len(batchedData))

                for batch, batchOrigI in enumerate(batchRandIxs):
                    batchInputs, batchTargetSparse, batchSeqLengths = batchedData[
                        batchOrigI]
                    batchTargetIxs, batchTargetVals, batchTargetShape = batchTargetSparse
                    feedDict = {
                        model.inputX: batchInputs,
                        model.targetIxs: batchTargetIxs,
                        model.targetVals: batchTargetVals,
                        model.targetShape: batchTargetShape,
                        model.seqLengths: batchSeqLengths
                    }

                    if level == 'cha':
                        if mode == 'train':
                            _, l, pre, y, er = sess.run([
                                model.optimizer, model.loss, model.predictions,
                                model.targetY, model.errorRate
                            ],
                                                        feed_dict=feedDict)

                            batchErrors[batch] = er
                            print(
                                '\n{} mode, total:{},batch:{}/{},epoch:{}/{},train loss={:.3f},mean train CER={:.3f}\n'
                                .format(level, totalN, batch + 1,
                                        len(batchRandIxs), epoch + 1,
                                        num_epochs, l, er / batch_size))

                        elif mode == 'test':
                            l, pre, y, er = sess.run([
                                model.loss, model.predictions, model.targetY,
                                model.errorRate
                            ],
                                                     feed_dict=feedDict)
                            batchErrors[batch] = er
                            print(
                                '\n{} mode, total:{},batch:{}/{},test loss={:.3f},mean test CER={:.3f}\n'
                                .format(level, totalN, batch + 1,
                                        len(batchRandIxs), l, er / batch_size))

                    elif level == 'phn':
                        if mode == 'train':
                            _, l, pre, y = sess.run([
                                model.optimizer, model.loss, model.predictions,
                                model.targetY
                            ],
                                                    feed_dict=feedDict)

                            er = get_edit_distance([pre.values], [y.values],
                                                   True, level)
                            print(
                                '\n{} mode, total:{},batch:{}/{},epoch:{}/{},train loss={:.3f},mean train PER={:.3f}\n'
                                .format(level, totalN, batch + 1,
                                        len(batchRandIxs), epoch + 1,
                                        num_epochs, l, er))
                            batchErrors[batch] = er * len(batchSeqLengths)
                        elif mode == 'test':
                            l, pre, y = sess.run(
                                [model.loss, model.predictions, model.targetY],
                                feed_dict=feedDict)
                            er = get_edit_distance([pre.values], [y.values],
                                                   True, level)
                            print(
                                '\n{} mode, total:{},batch:{}/{},test loss={:.3f},mean test PER={:.3f}\n'
                                .format(level, totalN, batch + 1,
                                        len(batchRandIxs), l, er))
                            batchErrors[batch] = er * len(batchSeqLengths)

                    # NOTE:
                    if er / batch_size == 1.0:
                        break

                    if batch % 30 == 0:
                        print('Truth:\n' + output_to_sequence(y, type=level))
                        print('Output:\n' +
                              output_to_sequence(pre, type=level))

                    if mode == 'train' and (
                        (epoch * len(batchRandIxs) + batch + 1) % 20 == 0 or
                        (epoch == num_epochs - 1
                         and batch == len(batchRandIxs) - 1)):
                        checkpoint_path = os.path.join(savedir, 'model.ckpt')
                        model.saver.save(sess,
                                         checkpoint_path,
                                         global_step=epoch)
                        print('Model has been saved in {}'.format(savedir))
                end = time.time()
                delta_time = end - start
                print('Epoch ' + str(epoch + 1) + ' needs time:' +
                      str(delta_time) + ' s')

                if mode == 'train':
                    if (epoch + 1) % 1 == 0:
                        checkpoint_path = os.path.join(savedir, 'model.ckpt')
                        model.saver.save(sess,
                                         checkpoint_path,
                                         global_step=epoch)
                        print('Model has been saved in {}'.format(savedir))
                    epochER = batchErrors.sum() / totalN
                    print('Epoch', epoch + 1, 'mean train error rate:',
                          epochER)
                    logging(model,
                            logfile,
                            epochER,
                            epoch,
                            delta_time,
                            mode='config')
                    logging(model,
                            logfile,
                            epochER,
                            epoch,
                            delta_time,
                            mode=mode)

                if mode == 'test':
                    with open(os.path.join(resultdir, level + '_result.txt'),
                              'a') as result:
                        result.write(output_to_sequence(y, type=level) + '\n')
                        result.write(
                            output_to_sequence(pre, type=level) + '\n')
                        result.write('\n')
                    epochER = batchErrors.sum() / totalN
                    print(' test error rate:', epochER)
                    logging(model, logfile, epochER, mode=mode)
Exemplo n.º 2
0
    def run(self):
        # load data
        args_dict = self._default_configs()

        args = dotdict(args_dict)

        feature_dirs, label_dirs = get_data(datadir, level, train_dataset,
                                            mode)

        FL_pair = list(zip(feature_dirs, label_dirs))

        feature_dirs, label_dirs = zip(*FL_pair)

        for feature_dir, label_dir in zip(feature_dirs, label_dirs):

            batchedData, maxTimeSteps, totalN = self.load_data(
                feature_dir, label_dir, mode, level)

            model = model_fn(args, maxTimeSteps)

            num_params = count_params(model, mode='trainable')
            all_num_params = count_params(model, mode='all')
            model.config['trainable params'] = num_params
            model.config['all params'] = all_num_params

            with tf.Session(graph=model.graph) as sess:

                print('Initializing')
                sess.run(model.initial_op)

                for epoch in range(num_epochs):
                    ## training
                    start = time.time()
                    if mode == 'train':
                        print('Epoch {} ...'.format(epoch + 1))

                    avgloss = 0

                    batchErrors = np.zeros(len(batchedData))

                    batchRandIxs = np.arange(len(batchedData))

                    for batch, batchOrigI in enumerate(batchRandIxs):
                        batchInputs, batchTargetSparse, batchSeqLengths = batchedData[
                            batchOrigI]
                        batchTargetIxs, batchTargetVals, batchTargetShape = batchTargetSparse

                        feedDict = {
                            model.inputX: batchInputs,
                            model.targetIxs: batchTargetIxs,
                            model.targetVals: batchTargetVals,
                            model.targetShape: batchTargetShape,
                            model.seqLengths: batchSeqLengths
                        }

                        if level == 'cha':
                            if mode == 'train':

                                _, l, pre, y, er = sess.run([
                                    model.optimizer, model.loss,
                                    model.predictions, model.targetY,
                                    model.errorRate
                                ],
                                                            feed_dict=feedDict)

                                batchErrors[batch] = er

                                avgloss = avgloss + l

                                print(
                                    '\n{} mode, total:{},batch:{}/{},epoch:{}/{},train loss={:.4f},mean train CER={:.4f}\n'
                                    .format(level, totalN, batch + 1,
                                            len(batchRandIxs), epoch + 1,
                                            num_epochs, l, er / batch_size))

                    end = time.time()
                    delta_time = end - start
                    print('Epoch ' + str(epoch + 1) + ' needs time:' +
                          str(delta_time) + ' s')

                    if mode == 'train':
                        ctcloss = avgloss / (8440 / batch_size)
                        print('avarage CTC loss = ', ctcloss)

                        if (epoch + 1) % 1 == 0:
                            checkpoint_path = os.path.join(
                                savedir, 'model.ckpt')
                            model.saver.save(sess,
                                             checkpoint_path,
                                             global_step=epoch + 1)
                            print('Model has been saved in {}'.format(savedir))
                        epochER = batchErrors.sum() / totalN
                        print('Epoch', epoch + 1, 'mean train error rate:',
                              epochER)
                        if epoch < 1:
                            logging(model,
                                    logfile,
                                    epochER,
                                    ctcloss,
                                    epoch,
                                    delta_time,
                                    mode='config')
                        logging(model,
                                logfile,
                                epochER,
                                ctcloss,
                                epoch,
                                delta_time,
                                mode=mode)
                        if epochER <= 0.003:
                            break
Exemplo n.º 3
0
    def run(self):
        # load data
        args_dict = self._default_configs()
        args = dotdict(args_dict)
        feature_dirs, label_dirs = get_data(datadir, level, train_dataset, dev_dataset, test_dataset, mode)
        batchedData, maxTimeSteps, totalN = self.load_data(feature_dirs[0], label_dirs[0], mode, level)
        model = model_fn(args, maxTimeSteps)

        ## shuffle feature_dir and label_dir by same order
        FL_pair = list(zip(feature_dirs, label_dirs))
        random.shuffle(FL_pair)
        feature_dirs, label_dirs = zip(*FL_pair)

        for feature_dir, label_dir in zip(feature_dirs, label_dirs):
            id_dir = feature_dirs.index(feature_dir)
            print('dir id:{}'.format(id_dir))
            batchedData, maxTimeSteps, totalN = self.load_data(feature_dir, label_dir, mode, level)
            model = model_fn(args, maxTimeSteps)
            num_params = count_params(model, mode='trainable')
            all_num_params = count_params(model, mode='all')
            model.config['trainable params'] = num_params
            model.config['all params'] = all_num_params
            print(model.config)
            with tf.Session(graph=model.graph) as sess:
                # restore from stored model
                if keep == True:
                    ckpt = tf.train.get_checkpoint_state(savedir)
                    if ckpt and ckpt.model_checkpoint_path:
                        model.saver.restore(sess, ckpt.model_checkpoint_path)
                        print('Model restored from:' + savedir)
                else:
                    print('Initializing')
                    sess.run(model.initial_op)

                for epoch in range(num_epochs):
                    ## training
                    start = time.time()
                    if mode == 'train':
                        print('Epoch {} ...'.format(epoch + 1))

                    batchErrors = np.zeros(len(batchedData))
                    batchRandIxs = np.random.permutation(len(batchedData))

                    for batch, batchOrigI in enumerate(batchRandIxs):
                        batchInputs, batchTargetSparse, batchSeqLengths = batchedData[batchOrigI]
                        batchTargetIxs, batchTargetVals, batchTargetShape = batchTargetSparse
                        feedDict = {model.inputX: batchInputs, model.targetIxs: batchTargetIxs,
                                    model.targetVals: batchTargetVals, model.targetShape: batchTargetShape,
                                    model.seqLengths: batchSeqLengths}

                        if level == 'cha':
                            if mode == 'train':
                                _, l, pre, y, er = sess.run([model.optimizer, model.loss,
                                    model.predictions, model.targetY, model.errorRate],
                                    feed_dict=feedDict)

                                batchErrors[batch] = er
                                print('\n{} mode, total:{},subdir:{}/{},batch:{}/{},epoch:{}/{},train loss={:.3f},mean train CER={:.3f}\n'.format(
                                    level, totalN, id_dir+1, len(feature_dirs), batch+1, len(batchRandIxs), epoch+1, num_epochs, l, er/batch_size))

                            elif mode == 'dev':
                                l, pre, y, er = sess.run([model.loss, model.predictions, 
                                    model.targetY, model.errorRate], feed_dict=feedDict)
                                batchErrors[batch] = er
                                print('\n{} mode, total:{},subdir:{}/{},batch:{}/{},dev loss={:.3f},mean dev CER={:.3f}\n'.format(
                                    level, totalN, id_dir+1, len(feature_dirs), batch+1, len(batchRandIxs), l, er/batch_size))

                            elif mode == 'test':
                                l, pre, y, er = sess.run([model.loss, model.predictions, 
                                    model.targetY, model.errorRate], feed_dict=feedDict)
                                batchErrors[batch] = er
                                print('\n{} mode, total:{},subdir:{}/{},batch:{}/{},test loss={:.3f},mean test CER={:.3f}\n'.format(
                                    level, totalN, id_dir+1, len(feature_dirs), batch+1, len(batchRandIxs), l, er/batch_size))
                        elif level=='seq2seq':
                            raise ValueError('level %s is not supported now'%str(level))


                        # NOTE:
                        if er / batch_size == 1.0:
                            break

                        if batch % 20 == 0:
                            print('Truth:\n' + output_to_sequence(y, type=level))
                            print('Output:\n' + output_to_sequence(pre, type=level))

                    
                        if mode=='train' and ((epoch * len(batchRandIxs) + batch + 1) % 20 == 0 or (
                            epoch == num_epochs - 1 and batch == len(batchRandIxs) - 1)):
                            checkpoint_path = os.path.join(savedir, 'model.ckpt')
                            model.saver.save(sess, checkpoint_path, global_step=epoch)
                            print('Model has been saved in {}'.format(savedir))

                    end = time.time()
                    delta_time = end - start
                    print('Epoch ' + str(epoch + 1) + ' needs time:' + str(delta_time) + ' s')

                    if mode=='train':
                        if (epoch + 1) % 1 == 0:
                            checkpoint_path = os.path.join(savedir, 'model.ckpt')
                            model.saver.save(sess, checkpoint_path, global_step=epoch)
                            print('Model has been saved in {}'.format(savedir))
                        epochER = batchErrors.sum() / totalN
                        print('Epoch', epoch + 1, 'mean train error rate:', epochER)
                        logging(model, logfile, epochER, epoch, delta_time, mode='config')
                        logging(model, logfile, epochER, epoch, delta_time, mode=mode)

                    if mode=='test' or mode=='dev':
                        with open(os.path.join(resultdir, level + '_result.txt'), 'a') as result:
                            result.write(output_to_sequence(y, type=level) + '\n')
                            result.write(output_to_sequence(pre, type=level) + '\n')
                            result.write('\n')
                        epochER = batchErrors.sum() / totalN
                        print(' test error rate:', epochER)
                        logging(model, logfile, epochER, mode=mode)
Exemplo n.º 4
0
        'rnncell': rnncell,
        'batch_size': batch_size,
        'num_hidden': num_hidden,
        'num_feature': num_feature,
        'num_class': num_classes,
        'num_layer': num_layer,
        'activation': activation_fn,
        'optimizer': optimizer_fn,
        'learning_rate': lr,
        'keep_prob': keep_prob,
        'grad_clip': grad_clip,
    }


args_dict = _default_configs()
args = dotdict(args_dict)


def do_eval(in_wav,
            winlen=winlen,
            winstep=winstep,
            preprocess_mode=preprocess_mode,
            featlen=featlen):
    feats = wav2feature(in_wav, winlen, winstep, preprocess_mode, featlen)
    batchedData, maxTimeSteps = data_lists_to_batches([np.array(feats)],
                                                      [[np.array(0)]],
                                                      batch_size, level,
                                                      max_time_slices)

    batchErrors = np.zeros(len(batchedData))
    batchRandIxs = np.random.permutation(len(batchedData))
Exemplo n.º 5
0
    def run(self):
        # load data
        for test in range(len(SNRdir)):

            args_dict = self._default_configs()
            args = dotdict(args_dict)

            feature_dirs, label_dirs = get_data(datadir, level, SNRdir[test],
                                                mode)

            filenamestr = os.listdir(feature_dirs[0])

            FL_pair = list(zip(feature_dirs, label_dirs))

            feature_dirs, label_dirs = zip(*FL_pair)

            for feature_dir, label_dir in zip(feature_dirs, label_dirs):

                batchedData, maxTimeSteps, totalN = self.load_data(
                    feature_dir, label_dir, mode, level)

                model = model_fn(args, maxTimeSteps)

                with tf.Session(graph=model.graph) as sess:
                    # restore from stored model
                    if keep == True:
                        ckpt = tf.train.get_checkpoint_state(savedir)
                        if ckpt and ckpt.model_checkpoint_path:
                            model.saver.restore(sess,
                                                ckpt.model_checkpoint_path)
                            print('Model restored from:' + savedir)

                    for epoch in range(num_epochs):

                        fnindex = 0  #used for write file name while testing

                        batchErrors = np.zeros(len(batchedData))

                        batchRandIxs = np.arange(len(batchedData))

                        for batch, batchOrigI in enumerate(batchRandIxs):
                            batchInputs, batchTargetSparse, batchSeqLengths = batchedData[
                                batchOrigI]
                            batchTargetIxs, batchTargetVals, batchTargetShape = batchTargetSparse

                            feedDict = {
                                model.inputX: batchInputs,
                                model.targetIxs: batchTargetIxs,
                                model.targetVals: batchTargetVals,
                                model.targetShape: batchTargetShape,
                                model.seqLengths: batchSeqLengths
                            }

                            if level == 'cha':

                                if mode == 'test':

                                    pre, er = sess.run(
                                        [model.predictions, model.errorRate],
                                        feed_dict=feedDict)

                                    batchErrors[batch] = er

                                    digit = output_to_sequence(pre, type=level)

                                    with open(
                                            os.path.join(
                                                resultdir,
                                                SNRdir[test] + '_results.MLF'),
                                            'a') as result:

                                        if batch < 1:

                                            result.write('#!MLF!#' + '\n')

                                            for i in range(batch_size):

                                                head = '"*/'

                                                tail = '.rec"'

                                                a = filenamestr[fnindex].split(
                                                    '.')

                                                fnindex = fnindex + 1

                                                labelstr = head + a[0] + tail

                                                result.write(labelstr + '\n')

                                                decode = digit[i]

                                                for j in range(len(decode)):
                                                    result.write(decode[j] +
                                                                 '\n')

                                                result.write('.' + '\n')

                                    print(
                                        '\n{} mode, total:{},batch:{}/{},mean test CER={:.4f}\n'
                                        .format(level, totalN, batch + 1,
                                                len(batchRandIxs),
                                                er / batch_size))
Exemplo n.º 6
0
    def run(self):
        # load data
        args_dict = self._default_configs()
        args = dotdict(args_dict)

        X, labels = get_data(level, train_dataset, test_dataset, mode)
        totalN = len(X)
        print("X :", len(X))
        num_batches = len(X) / batch_size
        maxLength = 0
        for x in X:
            maxLength = max(maxLength, x.shape[1])
        if (maxLength % 5000 != 0):
            maxLength = maxLength + 5000 - maxLength % 5000

        #batchedData, maxTimeSteps, totalN = self.load_data(X,labels,batch_size,mode,level)
        maxTimeSteps = maxLength
        model = model_fn(args, maxTimeSteps)
        model.build_graph(args, maxTimeSteps)
        #print("hello")
        #num_params = count_params(model, mode='trainable')
        #all_num_params = count_params(model, mode='all')
        #model.config['trainable params'] = num_params
        #model.config['all params'] = all_num_params
        print(model.config)

        with tf.Session(graph=model.graph) as sess:
            # restore from stored model
            if keep == True:
                ckpt = tf.train.get_checkpoint_state(savedir)
                if ckpt and ckpt.model_checkpoint_path:
                    model.saver.restore(sess, ckpt.model_checkpoint_path)
                    print('Model restored from:' + savedir)
                else:
                    sess.run(model.initial_op)
            else:
                print('Initializing')
                sess.run(model.initial_op)

            if (mode == 'train'):
                writer = tf.summary.FileWriter("loggingdir", graph=model.graph)
                for epoch in range(num_epochs):
                    # training
                    start = time.time()
                    print('Epoch {} ...'.format(epoch + 1))

                    batchErrors = np.zeros(num_batches)
                    batchRandIxs = np.random.permutation(num_batches)
                    for batch, batchOrigI in enumerate(batchRandIxs):
                        batchInputs, batchTargetSparse, batchSeqLengths = next(
                            load_batched_data(X, labels, batch_size, mode,
                                              level))
                        batchTargetIxs, batchTargetVals, batchTargetShape = batchTargetSparse
                        feedDict = {
                            model.inputX: batchInputs,
                            model.targetIxs: batchTargetIxs,
                            model.targetVals: batchTargetVals,
                            model.targetShape: batchTargetShape,
                            model.seqLengths: batchSeqLengths
                        }
                        if level == 'cha':
                            _, l, pre, y, er, summary = sess.run(
                                [
                                    model.optimizer, model.loss,
                                    model.predictions, model.targetY,
                                    model.errorRate, model.summary_op
                                ],
                                feed_dict=feedDict)
                            writer.add_summary(summary,
                                               epoch * num_batches + batch)

                            batchErrors[batch] = er
                            print(
                                '\n{} mode, batch:{}/{},epoch:{}/{},train loss={:.3f},mean train CER={:.3f}\n'
                                .format(level, batch + 1, len(batchRandIxs),
                                        epoch + 1, num_epochs, l,
                                        er / batch_size))

                        if (batch + 1) % 10 == 0:
                            print('Truth:\n' +
                                  output_to_sequence(y, type='phn'))
                            print('Output:\n' +
                                  output_to_sequence(pre, type='phn'))

                        if ((epoch * len(batchRandIxs) + batch + 1) % 20 == 0
                                or (epoch == num_epochs - 1
                                    and batch == len(batchRandIxs) - 1)):
                            checkpoint_path = os.path.join(
                                savedir, 'model.ckpt')
                            model.saver.save(sess,
                                             checkpoint_path,
                                             global_step=epoch)
                            print('Model has been saved in {}'.format(savedir))

                    end = time.time()
                    delta_time = end - start
                    print('Epoch ' + str(epoch + 1) + ' needs time:' +
                          str(delta_time) + ' s')

                    if (epoch + 1) % 1 == 0:
                        checkpoint_path = os.path.join(savedir, 'model.ckpt')
                        model.saver.save(sess,
                                         checkpoint_path,
                                         global_step=epoch)
                        print('Model has been saved in {}'.format(savedir))
                    epochER = batchErrors.sum() / totalN
                    print('Epoch', epoch + 1, 'mean train error rate:',
                          epochER)
                    logging(model,
                            logfile,
                            epochER,
                            epoch,
                            delta_time,
                            mode='config')
                    logging(model,
                            logfile,
                            epochER,
                            epoch,
                            delta_time,
                            mode=mode)

            elif (mode == 'test'):
                for data in load_batched_data(X, labels, batch_size, mode,
                                              level):
                    batchInputs, batchTargetSparse, batchSeqLengths = data
                    batchTargetIxs, batchTargetVals, batchTargetShape = batchTargetSparse
                    feedDict = {
                        model.inputX: batchInputs,
                        model.targetIxs: batchTargetIxs,
                        model.targetVals: batchTargetVals,
                        model.targetShape: batchTargetShape,
                        model.seqLengths: batchSeqLengths
                    }
                    _, l, pre, y, er = sess.run([
                        model.optimizer, model.loss, model.predictions,
                        model.targetY, model.errorRate
                    ],
                                                feed_dict=feedDict)
                    with open(os.path.join(resultdir, level + '_result.txt'),
                              'a') as result:
                        result.write(output_to_sequence(y, type='phn') + '\n')
                        result.write(
                            output_to_sequence(pre, type='phn') + '\n')
                        result.write('\n')
                        #epochER = batchErrors.sum() / totalN
                        print(' test error rate:', epochER)
                        logging(model, logfile, epochER, mode=mode)