Example #1
0
 def next(self):
     seqs = []
     try:
         while len(seqs) < self.batch_size:
             line = next(self.txt_file).strip()
             seq, _ = parse_input(self.state, self.indx, line, raise_unk=self.raise_unk,
                                  unk_sym=self.unk_sym, null_sym=self.null_sym)
             seqs.append(seq)
         return self._pack(seqs)
     except StopIteration:
         if not seqs:
             raise StopIteration()
         return self._pack(seqs)
Example #2
0
def main():
    args = parse_args()

    state = prototype_state()
    with open(args.state) as src:
        state.update(cPickle.load(src))
    state.update(eval("dict({})".format(args.changes)))

    state['sort_k_batches'] = 1
    state['shuffle'] = False
    state['use_infinite_loop'] = False
    state['force_enc_repr_cpu'] = False

    logging.basicConfig(level=getattr(logging, state['level']), format="%(asctime)s: %(name)s: %(levelname)s: %(message)s")

    rng = numpy.random.RandomState(state['seed'])
    enc_dec = RNNEncoderDecoder(state, rng, skip_init=True, compute_alignment=True)
    enc_dec.build()
    lm_model = enc_dec.create_lm_model()
    lm_model.load(args.model_path)

    indx_word_src = cPickle.load(open(state['word_indx'],'rb'))
    indx_word_trgt = cPickle.load(open(state['word_indx_trgt'], 'rb'))

    if args.mode == "batch":
        data_given = args.src or args.trg
        txt = data_given and not (args.src.endswith(".h5") and args.trg.endswith(".h5"))
        if data_given and not txt:
            state['source'] = [args.src]
            state['target'] = [args.trg]
        if not data_given and not txt:
            logger.info("Using the training data")
        if txt:
            data_iter = BatchBiTxtIterator(state,
                    args.src, indx_word_src, args.trg, indx_word_trgt,
                    state['bs'], raise_unk=not args.allow_unk)
            data_iter.start()
        else:
            data_iter = get_batch_iterator(state)
            data_iter.start(0)

        score_file = open(args.scores, "w") if args.scores else sys.stdout

        scorer = enc_dec.create_scorer(batch=True)

        count = 0
        n_samples = 0
        logger.info('Scoring phrases')
        for i, batch in enumerate(data_iter):
            if batch == None:
                continue
            if args.n_batches >= 0 and i == args.n_batches:
                break

            if args.y_noise:
                y = batch['y']
                random_words = numpy.random.randint(0, 100, y.shape).astype("int64")
                change_mask = numpy.random.binomial(1, args.y_noise, y.shape).astype("int64")
                y = change_mask * random_words + (1 - change_mask) * y
                batch['y'] = y

            st = time.time()
            [scores] = scorer(batch['x'], batch['y'],
                    batch['x_mask'], batch['y_mask'])
            if args.print_probs:
                scores = numpy.exp(scores)
            up_time = time.time() - st
            for s in scores:
                print >>score_file, "{:.5e}".format(float(s))

            n_samples += batch['x'].shape[1]
            count += 1

            if count % 100 == 0:
                score_file.flush()
                logger.debug("Scores flushed")
            logger.debug("{} batches, {} samples, {} per sample; example scores: {}".format(
                count, n_samples, up_time/scores.shape[0], scores[:5]))

        logger.info("Done")
        score_file.flush()
    elif args.mode == "interact":
        scorer = enc_dec.create_scorer()
        while True:
            try:
                compute_probs = enc_dec.create_probs_computer()
                src_line = raw_input('Source sequence: ')
                trgt_line = raw_input('Target sequence: ')
                src_seq = parse_input(state, indx_word_src, src_line, raise_unk=not args.allow_unk, 
                                      unk_sym=state['unk_sym_source'], null_sym=state['null_sym_source'])
                trgt_seq = parse_input(state, indx_word_trgt, trgt_line, raise_unk=not args.allow_unk,
                                       unk_sym=state['unk_sym_target'], null_sym=state['null_sym_target'])
                print "Binarized source: ", src_seq
                print "Binarized target: ", trgt_seq
                probs = compute_probs(src_seq, trgt_seq)
                print "Probs: {}, cost: {}".format(probs, -numpy.sum(numpy.log(probs)))
            except Exception:
                traceback.print_exc()
    elif args.mode == "txt":
        assert args.src and args.trg
        scorer = enc_dec.create_scorer()
        src_file = open(args.src, "r")
        trg_file = open(args.trg, "r")
        compute_probs = enc_dec.create_probs_computer(return_alignment=True)
        try:
            numpy.set_printoptions(precision=3, linewidth=150, suppress=True)
            i = 0
            while True:
                src_line = next(src_file).strip()
                trgt_line = next(trg_file).strip()
                src_seq, src_words = parse_input(state,
                        indx_word_src, src_line, raise_unk=not args.allow_unk,
                        unk_sym=state['unk_sym_source'], null_sym=state['null_sym_source'])
                trgt_seq, trgt_words = parse_input(state,
                        indx_word_trgt, trgt_line, raise_unk=not args.allow_unk,
                        unk_sym=state['unk_sym_target'], null_sym=state['null_sym_target'])
                probs, alignment = compute_probs(src_seq, trgt_seq)
                if args.verbose:
                    print "Probs: ", probs.flatten()
                    if alignment.ndim == 3:
                        print "Alignment:".ljust(20), src_line, "<eos>"
                        for i, word in enumerate(trgt_words):
                            print "{}{}".format(word.ljust(20), alignment[i, :, 0])
                        print "Generated by:"
                        for i, word in enumerate(trgt_words):
                            j = numpy.argmax(alignment[i, :, 0])
                            print "{} <--- {}".format(word,
                                    src_words[j] if j < len(src_words) else "<eos>")
                i += 1
                if i % 100 == 0:
                    sys.stdout.flush()
                    logger.debug(i)
                print -numpy.sum(numpy.log(probs))
        except StopIteration:
            pass
    else:
        raise Exception("Unknown mode {}".format(args.mode))
Example #3
0
def main():
    args = parse_args()

    state = getattr(experiments.nmt, args.state_fn)()
    if hasattr(args, 'state') and args.state:
        with open(args.state) as src:
            state.update(cPickle.load(src))
    state.update(eval("dict({})".format(args.changes)))

    assert state['enc_rec_layer'] == "RecursiveConvolutionalLayer", "Only works with gated recursive convolutional encoder"

    logging.basicConfig(level=getattr(logging, state['level']), format="%(asctime)s: %(name)s: %(levelname)s: %(message)s")

    rng = numpy.random.RandomState(state['seed'])
    enc_dec = RNNEncoderDecoder(state, rng, skip_init=True)
    enc_dec.build()
    lm_model = enc_dec.create_lm_model()
    lm_model.load(args.model_path)

    indx_word = cPickle.load(open(state['word_indx'],'rb'))
    idict_src = cPickle.load(open(state['indx_word'],'r'))

    x = TT.lvector()
    h = TT.tensor3()

    proj_x = theano.function([x], enc_dec.encoder.input_embedders[0](
        enc_dec.encoder.approx_embedder(x)).out, name='proj_x')
    new_h, gater = enc_dec.encoder.transitions[0].step_fprop(
        None, h, return_gates = True)
    step_up = theano.function([h], [new_h, gater], name='gater_step')

    while True:
        try:
            seqin = raw_input('Input Sequence: ')
            seq,parsed_in = parse_input(state, indx_word, seqin, idx2word=idict_src)
            print "Parsed Input:", parsed_in
        except Exception:
            print "Exception while parsing your input:"
            traceback.print_exc()
            continue

        # get the initial embedding
        new_h = proj_x(seq)
        new_h = new_h.reshape(new_h.shape[0], 1, new_h.shape[1])

        nodes = numpy.arange(len(seq)).tolist()
        node_idx = len(seq)-1
        rules = []
        nodes_level = copy.deepcopy(nodes)

        G = nx.DiGraph()

        input_nodes = []
        merge_nodes = []
        aggregate_nodes = []

        nidx = 0 
        vpos = 0
        nodes_pos = {}
        nodes_labels = {}
        # input nodes
        for nn in nodes[:-1]:
            nidx += 1
            G.add_node(nn, pos=(nidx, 0), ndcolor="blue", label="%d"%nn)
            nodes_pos[nn] = (nidx, vpos)
            nodes_labels[nn] = idict_src[seq[nidx-1]]
            input_nodes.append(nn)
        node_idx = len(seq) - 1

        vpos += 6
        for dd in xrange(len(seq)-1):
            new_h, gater = step_up(new_h)
            decisions = numpy.argmax(gater, -1)
            new_nodes_level = numpy.zeros(len(seq) - (dd+1))
            hpos = float(len(seq)+1) - 0.5 * (dd+1)
            last_node = True
            for nn in xrange(len(seq)-(dd+1)):
                hpos -= 1
                if not last_node:
                    # merge nodes
                    node_idx += 1
                    G.add_node(node_idx, ndcolor="red", label="m")
                    nodes_labels[node_idx] = ""
                    nodes_pos[node_idx] = (hpos, vpos)
                    G.add_edge(nodes_level[-(nn+1)], node_idx, weight=gater[-(nn+1),0,0])
                    G.add_edge(nodes_level[-(nn+2)], node_idx, weight=gater[-(nn+1),0,0])
                    merge_nodes.append(node_idx)

                    merge_node = node_idx
                    # linear aggregation nodes
                    node_idx += 1
                    G.add_node(node_idx, ndcolor="red", label="")
                    nodes_labels[node_idx] = "$+$"
                    nodes_pos[node_idx] = (hpos, vpos+6)
                    G.add_edge(merge_node, node_idx, weight=gater[-(nn+1),0,0])
                    G.add_edge(nodes_level[-(nn+2)], node_idx, weight=gater[-(nn+1),0,1])
                    G.add_edge(nodes_level[-(nn+1)], node_idx, weight=gater[-(nn+1),0,2])
                    aggregate_nodes.append(node_idx)

                    new_nodes_level[-(nn+1)] = node_idx
                last_node = False
            nodes_level = copy.deepcopy(new_nodes_level)
            vpos += 12

        # TODO: Show only strong edges.
        threshold = float(raw_input('Threshold: '))
        edges = [(u,v,d) for (u,v,d) in G.edges(data=True) if d['weight'] > threshold]
        #edges = G.edges(data=True)

        use_weighting = raw_input('Color according to weight [Y/N]: ')
        if use_weighting == 'Y':
            cm = plt.get_cmap('binary') 
            cNorm  = colors.Normalize(vmin=0., vmax=1.)
            scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
            colorList = [scalarMap.to_rgba(d['weight']) for (u,v,d) in edges]
        else:
            colorList = 'k'

        nx.draw_networkx_nodes(G, pos=nodes_pos, nodelist=input_nodes, node_color='white', alpha=1., edge_color='white')
        nx.draw_networkx_nodes(G, pos=nodes_pos, nodelist=merge_nodes, node_color='blue', alpha=0.8, node_size=20)
        nx.draw_networkx_nodes(G, pos=nodes_pos, nodelist=aggregate_nodes, node_color='red', alpha=0.8, node_size=80)
        nx.draw_networkx_edges(G, pos=nodes_pos, edge_color=colorList, edgelist=edges)
        nx.draw_networkx_labels(G,pos=nodes_pos,labels=nodes_labels,font_family='sans-serif')
        plt.axis('off')
        figname = raw_input('Save to: ')
        if figname[-3:] == "pdf":
            plt.savefig(figname, type='pdf')
        else:
            plt.savefig(figname)
        plt.close()
        G.clear()
Example #4
0
def main():
    args = parse_args()

    state = prototype_state()
    with open(args.state) as src:
        state.update(cPickle.load(src))
    state.update(eval("dict({})".format(args.changes)))

    logging.basicConfig(level=getattr(logging, state['level']), format="%(asctime)s: %(name)s: %(levelname)s: %(message)s")

    rng = numpy.random.RandomState(state['seed'])
    enc_dec = RNNEncoderDecoder(state, rng, skip_init=True)
    enc_dec.build()
    lm_model = enc_dec.create_lm_model()
    lm_model.load(args.model_path)
    indx_word = cPickle.load(open(state['word_indx'],'rb'))

    sampler = None
    beam_search = None
    if args.beam_search:
        beam_search = BeamSearch(enc_dec)
        beam_search.compile()
    else:
        sampler = enc_dec.create_sampler(many_samples=True)

    idict_src = cPickle.load(open(state['indx_word'],'r'))

    if args.source and args.trans:
        # Actually only beam search is currently supported here
        assert beam_search
        assert args.beam_size

        fsrc = open(args.source, 'r')
        ftrans = open(args.trans, 'w')

        start_time = time.time()

        n_samples = args.beam_size
        total_cost = 0.0
        logging.debug("Beam size: {}".format(n_samples))
        for i, line in enumerate(fsrc):
            seqin = line.strip()
            seq, parsed_in = parse_input(state, indx_word, seqin, idx2word=idict_src)
            if args.verbose:
                print "Parsed Input:", parsed_in
            trans, costs, _ = sample(lm_model, seq, n_samples, sampler=sampler,
                    beam_search=beam_search, ignore_unk=args.ignore_unk, normalize=args.normalize)
            best = numpy.argmin(costs)
            print >>ftrans, trans[best]
            if args.verbose:
                print "Translation:", trans[best]
            total_cost += costs[best]
            if (i + 1)  % 100 == 0:
                ftrans.flush()
                logger.debug("Current speed is {} per sentence".
                        format((time.time() - start_time) / (i + 1)))
        print "Total cost of the translations: {}".format(total_cost)

        fsrc.close()
        ftrans.close()
    else:
        while True:
            try:
                seqin = raw_input('Input Sequence: ')
                n_samples = int(raw_input('How many samples? '))
                alpha = None
                if not args.beam_search:
                    alpha = float(raw_input('Inverse Temperature? '))
                seq,parsed_in = parse_input(state, indx_word, seqin, idx2word=idict_src)
                print "Parsed Input:", parsed_in
            except Exception:
                print "Exception while parsing your input:"
                traceback.print_exc()
                continue

            sample(lm_model, seq, n_samples, sampler=sampler,
                    beam_search=beam_search,
                    ignore_unk=args.ignore_unk, normalize=args.normalize,
                    alpha=alpha, verbose=True)
Example #5
0
def process_sentence(source_sentence, model, max_phrase_length, n_samples,
                     copy_UNK_words, add_period, normalize, reverse_score):

    #Setting up comp_score function
    logger.debug("setting up comp_score function")
    [lm_model, enc_dec, indx_word_src, indx_word_trgt, state, \
            lm_model_fr_2_en, enc_dec_fr_2_en, state_fr2en] = model

    eol_src = state['null_sym_source']
    src_seq = parse_input(state, indx_word_src, source_sentence)
    if src_seq[-1] == eol_src:
        src_seq = src_seq[:-1]
    n_s = len(src_seq)

    #Create sorted phrase lists
    tiled_source_phrase_list = []
    index_order_list = []
    for i in xrange(n_s):
        for j in numpy.arange(i, min(i+max_phrase_length, n_s)):
                    index_order_list.append([i, j])

    logger.debug("sorting list")
    index_order_list.sort(key=lambda (i, j): (j - i))

    logger.debug("creating phrase lists")
    if add_period:
        period_src = indx_word_src['.']
        for i, j in index_order_list:
            tiled_source_phrase_list.append(numpy.hstack((src_seq[i:j+1], period_src, eol_src)))
    else:
        for i, j in index_order_list:
            tiled_source_phrase_list.append(numpy.hstack((src_seq[i:j+1], eol_src)))


    #Compute nested score dictionary
    logger.debug("computing nested score dictionary")
    score_dict = {}
    trans = {}

    for phrase_idx in xrange(0, len(index_order_list)):
        logger.debug("{0} out of {1}".format(phrase_idx, len(index_order_list)))
        i, j = index_order_list[phrase_idx]
        logger.debug("Translating phrase : {}".format(" ".join(source_sentence.strip().split()[i:j+1])))

        if copy_UNK_words == True:
            phrase_to_translate = tiled_source_phrase_list[phrase_idx]
            n_UNK_words = numpy.sum([word == 1 for word in phrase_to_translate])
            if n_UNK_words >= 1 and n_UNK_words == len(phrase_to_translate) - 1:
                suggested_translation = " ".join(source_sentence.strip().split()[i:j+1])
                trans[i, j] = suggested_translation
                score = .0001
                score_dict[i, j] = score
            if n_UNK_words >= 1 and n_UNK_words != len(phrase_to_translate) -1:
                suggested_translation = "WILL NOT BE USED"
                trans[i, j] = suggested_translation
                score = 1e9
                score_dict[i, j] = score
            if n_UNK_words == 0:
                suggested_translation, score = sample_targets(
                                                    input_phrase= \
                                                           tiled_source_phrase_list[phrase_idx],
                                                    model=model,
                                                    n_samples=n_samples,
                                                    reverse_score=reverse_score,
                                                    normalize=normalize
                )
                trans[i, j] = suggested_translation
                score_dict[i, j] = score

        else:
            phrase_to_translate = tiled_source_phrase_list[phrase_idx]
            suggested_translation, score = sample_targets(
                                                input_phrase=phrase_to_translate,
                                                model=model, n_samples=n_samples,
                                                reverse_score=reverse_score,
                                                normalize=normalize
            )
            trans[i, j] = suggested_translation
            score_dict[i, j] = score

    #Remove the period at the end if not last word
    #Lower case first word if not first word
    if add_period:
       for phrase_idx in xrange(0, len(index_order_list)):
           i, j = index_order_list[phrase_idx]
           if i != 0:
               trans[i, j] = " ".join([trans[i,j][0].lower()] + [trans[i,j][1:]])
           if j != len(src_seq) - 1:
               last_word = trans[i,j].strip().split()[-1]
               if last_word == '.':
                   trans[i,j] = " ".join(trans[i,j].strip().split()[:-1])


    #Translation of full sentence without segmentation
    logger.debug("Translating full sentence")
    phrase_to_translate = numpy.hstack((src_seq, eol_src))
    full_translation, __ = sample_targets(input_phrase=phrase_to_translate,
                                          model=model,
                                          n_samples=n_samples,
                                          reverse_score=reverse_score,
                                          normalize=normalize
    )
    logger.debug("Translation output:".format(full_translation))

    return trans, score_dict, full_translation