main.py 2.63 KB
import numpy
import time
import sys
import subprocess
import os
import random

from modules.data import load
from modules.rnn.nnet_for_dependency_trees import model
#from modules.metrics.accuracy import conlleval
from modules.utils.tools import shuffle, words_in_from_down_to_top_order, load_conll_data

import theano.tensor as T
import theano

import itertools




if __name__ == '__main__':

    s = {'lr':0.0627142536696559,
         'verbose':1,
         'decay':False, # decay on the learning rate if improvement stops
         'nepochs':5,
         'seed':345,
         'nh':5, # dimension of hidden state
         'nc':2 , # number of y classes
         'ds':5}  # dimension of sentiment state



    # instanciate the model
    numpy.random.seed(s['seed'])
    random.seed(s['seed'])
    rnn = model(    nh = s['nh'],
                    nc = s['nc'],
                    ds = s['ds'],
                    w2v_model_path = "embeddings/embeddings_tmp.pkl", #sciezka do pliku z embeddingami - te podane tutaj sa tylko przeykladowym plikiem
                    max_phrase_length = 50 # przydaloby sie to uzaleznic od danych, ale nie jest to konieczne. 
                                           # Wazne, ze to jest wartosc nie mniejsza niz dlugosc najdluzszego zdania w danych
                    )

    conll_format_data = 'data/slowa.conll'
    data = load_conll_data(conll_format_data, rnn.words2ids)
    # UWAGA: w pliku ekstowym zawierajacym frazy w conll na koncu musza byc dwie puste linie
    
    train_data = data[0:int(0.9*len(data))]
    test_data = data[int(0.9*len(data)):len(data)]

    n_train_phrases = len(train_data)
    n_test_phrases = len(test_data)
    #to do: training with early stopping on validation set
   
    s['clr'] = s['lr']
    for e in xrange(s['nepochs']):
        # shuffle
        #shuffle([data], s['seed'])
        #s['ce'] = e
        tic = time.time()
        for i in range(n_train_phrases):
            #print(rnn.f(data[i][0],data[i][1], data[i][2]))
            rnn.train(train_data[i][0],train_data[i][1], train_data[i][2], train_data[i][3], s['clr'])
            #rnn.normalize()
            #if s['verbose']:
            #    print ('[learning] epoch %i >> %2.2f%%'%(e,(i+1)*100./n_train_phrases),'completed in %.2f (sec) <<\r'%(time.time()-tic))
            #    sys.stdout.flush()

        # Test:
        accuracy = 0.0
        for i in range(n_test_phrases):
            accuracy += int(test_data[i][3] == rnn.classify(test_data[i][0],test_data[i][1], test_data[i][2]))
            #print(test_data[i][3],rnn.classify(test_data[i][0],test_data[i][1], test_data[i][2]),accuracy)
        print(accuracy/n_test_phrases)