STACKEDAE_MODELS.py 7.39 KB
# coding: utf-8

# In[2]:

# Import
import pandas
# Alignement
import nltk
import codecs
import gensim
from scipy import sparse
import itertools
from sklearn.feature_extraction.text import CountVectorizer
import scipy.sparse
import scipy.io
from sklearn import preprocessing
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation,AutoEncoder
from keras.optimizers import SGD,Adam
from keras.layers import containers
from mlp import *
import mlp
import sklearn.metrics
import shelve
import pickle
from utils import *
import sys
import json
import itertools
# In[4]:

db=shelve.open("{}.shelve".format(sys.argv[2]),writeback=True)

sparse_model=shelve.open("{}.shelve".format(sys.argv[1]))
#['ASR', 'TRS', 'LABEL']
# In[6]:

ASR=sparse_model["ASR"]
TRS=sparse_model["TRS"]
LABEL=sparse_model["LABEL"]

db["ASR_SPARSE"]=ASR
db["TRS_SPARSE"]=TRS
db["LABEL"]=LABEL
print "todo label"
def select(elm):
    return int(elm.split("_")[-1])
#z.apply(select)
label_bin={}
lb = preprocessing.LabelBinarizer(neg_label=0)
lb.fit(LABEL["TRAIN"].apply(select))
for i in ASR.keys():
    label_bin=lb.transform(LABEL[i].apply(select))

hidden_size=50
input_activation="tanh"
out_activation="tanh"
loss="mse"
epochs=500
batch=1
patience=60
w1_size=300
w2_size=500
do_do=True
sgd = Adam(lr=0.0001)#SGD(lr=0.00001,nesterov=False) #'rmsprop'# Adam(lr=0.00001)#SGD(lr=0.001, momentum=0.9, nesterov=True)
try :
    sgd_repr=sgd.get_config()
except AttributeError :
    sgd_repr=sgd
json.dump({ "h1" : hidden_size,
	"inside_activation" : input_activation,
	"out_activation" : out_activation,
        "do_dropout": do_do,
	"loss" : loss,
	"epochs" : epochs ,
	"batch_size" : batch,
	"patience" : patience,
        "sgd" : sgd_repr},
	open("{}.json".format(sys.argv[2]),"w"),
	indent=4)
def fintuned(sized,x_data,y_data,input_activation,do_do):
    ae = Sequential()
    previous = x_data["TRAIN"].shape[1]
    for hidden_size,w in sized:
        ae.add(Dense(hidden_size,input_dim=previous,activation=input_activation,weights=w[:2]))
        if do_do :
            ae.add(Dropout(0.5))
        previous = hidden_size
    ae.compile(sgd,loss)
    hist = ae.fit(x_data["TRAIN"].todense(),y_data["TRAIN"].todense(),nb_epoch=epochs,batch_size=batch,
            callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss',
            patience=patience, verbose=0)],validation_data=(x_data["DEV"].todense(),y_data["DEV"].todense()),verbose=1)
    return (ae.get_weights(),hist)
def get_projection(weights,x_data):
    proj_list=[x_data]
    lappend=proj_list.append
    for w in zip(weights[0::2],weights[1::2]) :
        decoder =Sequential()
        decoder.add(Dense(w[1].shape[0],input_dim=proj_list[-1]["TRAIN"].shape[1],weights=w))
        decoder.compile(sgd,loss)
        lappend({})
        for key in proj_list[-2].keys():
            try : 
                proj_list[-1][key]=decoder.predict(proj_list[-2][key])
            except :
                proj_list[-1][key]=decoder.predict(proj_list[-2][key].todense())
    return proj_list
def learn_ae(hidden_size,data,do_do,input_activation,output_activation):
    autoencode=Sequential()
    autoencode.add(Dense(hidden_size,input_dim=data["TRAIN"].shape[1],init='glorot_uniform',activation=input_activation))
    if do_do :
        autoencode.add(Dropout(0.5))
    try : 
        autoencode.add(Dense(data["DEV"].todense().shape[1],input_dim=hidden_size,init="glorot_uniform",activation=out_activation))
        autoencode.compile(optimizer=sgd,loss=loss)
        hist =autoencode.fit(data["TRAIN"].todense(),data["TRAIN"].todense(),nb_epoch=epochs,batch_size=batch,
                           callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss',
                           patience=patience, verbose=0)],validation_data=(data["DEV"].todense(),data["DEV"].todense()),verbose=1)

        auto_decoder=Sequential()
        auto_decoder.add(Dense(hidden_size,input_dim=data["DEV"].todense().shape[1],init='uniform',activation=input_activation,weights=autoencode.get_weights()[:2]))
        auto_decoder.compile(optimizer=sgd,loss=loss)
        data_proj={}
        for i in data.keys():
            data_proj[i]=auto_decoder.predict(data[i].todense())
        return (data_proj,(hist.epoch,hist.history),autoencode.get_weights())


    except AttributeError :
        autoencode.add(Dense(data["DEV"].shape[1],input_dim=hidden_size,init="glorot_uniform",activation=out_activation))
        autoencode.compile(optimizer=sgd,loss=loss)
        hist =autoencode.fit(data["TRAIN"],data["TRAIN"],nb_epoch=epochs,batch_size=batch,
                           callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss',
                           patience=patience, verbose=0)],validation_data=(data["DEV"],data["DEV"]),verbose=1)

        auto_decoder=Sequential()
        auto_decoder.add(Dense(hidden_size,input_dim=data["DEV"].shape[1],init='uniform',activation=input_activation,weights=autoencode.get_weights()[:2]))
        auto_decoder.compile(optimizer=sgd,loss=loss)

        data_proj={}
        for i in data.keys():
            data_proj[i]=auto_decoder.predict(data[i])
        return (data_proj,(hist.epoch,hist.history),autoencode.get_weights())



print "gogo autoencoder ASR"
hist = {} 

ASR_AE_H1,hist["ASR_AE_H1"],wa1=learn_ae(hidden_size,ASR,do_do,input_activation,out_activation)
db["ASR_AE_H1"]=ASR_AE_H1
ASR_AE_H2,hist["ASR_AE_H2"],wa2=learn_ae(w1_size,ASR_AE_H1,do_do,input_activation,out_activation)
db["ASR_AE_H2"]=ASR_AE_H2
ASR_AE_H3,hist["ASR_AE_H3"],wa3=learn_ae(hidden_size,ASR_AE_H2,do_do,input_activation,out_activation)
db["ASR_AE_H3"]=ASR_AE_H3
ASR_AE_H4,hist["ASR_AE_H4"],wa4=learn_ae(ASR["TRAIN"].shape[1],ASR_AE_H3,do_do,input_activation,out_activation)
db["ASR_AE_OUT"]=ASR_AE_H4
db.sync()
print "fine_tuning"

w,h=fintuned([(hidden_size,wa1),(w1_size,wa2),(hidden_size,wa3),(ASR["TRAIN"].shape[1],wa4)],ASR,ASR,input_activation,do_do)
hist["finetuning_a2a"] = (h.epoch,h.history)
for k,proj in enumerate(get_projection(w,ASR)):
    db["ASR_AE_FTA2A_H"+str(k)]=proj


w,h=fintuned([(hidden_size,wa1),(w1_size,wa2),(hidden_size,wa3),(ASR["TRAIN"].shape[1],wa4)],ASR,TRS,input_activation,do_do)
hist["finetuning_a2t"] = (h.epoch,h.history)
for k,proj in enumerate(get_projection(w,ASR)):
    db["ASR_AE_FTA2T_H"+str(k)]=proj

print "auto encoder trs learning"
TRS_AE_H1,hist["TRS_AE_H1"],wt1=learn_ae(hidden_size,TRS,do_do,input_activation,out_activation)
db["TRS_AE_H1"]=TRS_AE_H1
TRS_AE_H2,hist["TRS_AE_H2"],wt2=learn_ae(w1_size,TRS_AE_H1,do_do,input_activation,out_activation)
db["TRS_AE_H2"]=TRS_AE_H2
TRS_AE_H3,hist["TRS_AE_H3"],wt3,=learn_ae(hidden_size,TRS_AE_H2,do_do,input_activation,out_activation)
db["TRS_AE_H3"]=TRS_AE_H3
TRS_AE_H4,hist["TRS_AE_H4"],wt4=learn_ae(TRS["TRAIN"].shape[1],TRS_AE_H3,do_do,input_activation,out_activation)
db["TRS_AE_OUT"]=TRS_AE_H4
db.sync()

w,h=fintuned([(hidden_size,wt1),(w1_size,wt2),(hidden_size,wt3),(ASR["TRAIN"].shape[1],wt4)],TRS,TRS,input_activation,do_do)
hist["finetuning_t2t"] = (h.epoch,h.history)
for k,proj in enumerate(get_projection(w,ASR)):
    db["ASR_AE_FTT2T_H"+str(k)]=proj


# In[261]:

#pred_dev= model_TRS_AE.predict(TRS_AE["DEV"],batch_size=1)

db.sync()
db.close()
json.dump({ "h1" : hidden_size,
	"inside_activation" : input_activation,
	"out_activation" : out_activation,
        "do_dropout": do_do,
	"loss" : loss,
	"epochs" : epochs ,
	"batch_size" : batch,
	"patience" : patience,
        "sgd" : sgd_repr,
        "hist" : hist},
	open("{}.json".format(sys.argv[2]),"w"),
	indent=4)