DECODA_binary_BOW_MINIAE_REAL_SPE.py 3.82 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
# In[4]:

db=shelve.open("{}.shelve".format(sys.argv[2]),writeback=True)
#['vocab', 'ASR_SPARSE', 'TRS_SPARSE', 'LABEL']
# In[6]:
# In[10]:
print "making sparse data"
sparse_corp=shelve.open("{}.shelve".format(sys.argv[1]))
do_do=False
try:
    do_do = True if sys.argv[3] == 1 else False
    hidden_size =[int(x) for x in sys.argv[4].split("_")] if sys.argv[4] else [100]
except IndexError :
    do_do = False
    hidden_size=[100]

ASR_sparse=sparse_corp["ASR"]
TRS_sparse=sparse_corp["TRS"]
db["LABEL"] = sparse_corp["LABEL"]
db["ASR"] = ASR_sparse
db["TRS"] = TRS_sparse
# In[11]:
#z.apply(select)
input_activation="tanh"
out_activation="tanh"
loss="mse"
epochs=500
batch=1
patience=60


sgd = Adam(lr=0.0001)#SGD(lr=0.0001)#( 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)




print "gogo autoencoder ASR"
done_do=False
autoencode=Sequential()
previous = ASR_sparse["TRAIN"].shape[1]
for hs in hidden_size:
    autoencode.add(Dense(hs,input_dim=previous,init='glorot_uniform',activation=input_activation))
    if do_do and not done_do:
        autoencode.add(Dropout(0.5))
        done_do=True
    previous = hs

autoencode.add(Dense(ASR_sparse["DEV"].todense().shape[1],input_dim=previous,init="glorot_uniform",activation=out_activation))

#autoencode.compile(optimizer=sgd,loss=loss)

autoencode.compile(optimizer=sgd,loss=loss)


# In[ ]:

autoencode.fit(ASR_sparse["TRAIN"].todense(),TRS_sparse["TRAIN"].todense(),nb_epoch=epochs,batch_size=batch,
               callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss',
                                                        patience=patience, verbose=0)],           validation_data=(ASR_sparse["DEV"].todense(),TRS_sparse["DEV"].todense()),verbose=1)


# In[ ]:

ASR_sparse_AE_H={}

previous=[ASR_sparse["DEV"].todense().shape[1]]
for i,size in enumerate(hidden_size):
    print previous,size
    print "i",i,range(i)
    auto_decoder=Sequential()
    for j in range(i):
        print "j",j
        auto_decoder.add(Dense(previous[j+1],input_dim=previous[j],init='glorot_uniform',activation=input_activation,weights=autoencode.get_weights()[j*2:j*2+2]))
    print "i",i,i*2,i*2+2

    auto_decoder.add(Dense(size,input_dim=previous[-1],init="glorot_uniform",activation=input_activation,weights=autoencode.get_weights()[i*2:i*2+2]))
    auto_decoder.compile(optimizer=sgd,loss=loss)
    previous.append(size)
    ASR_sparse_AE_H["H"+str(i)]={}
    for key in ASR_sparse.keys():
        ASR_sparse_AE_H["H"+str(i)][key]=auto_decoder.predict(ASR_sparse[key].todense())

    db["ASR_AE_H"+str(i)]=ASR_sparse_AE_H["H"+str(i)]
    del auto_decoder



db.sync()




# In[261]:

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

TRS_AE={}
ASR_AE={}
for i in TRS_sparse.keys():
    TRS_AE[i]=autoencode.predict(TRS_sparse[i].todense())
    ASR_AE[i]=autoencode.predict(ASR_sparse[i].todense())


db["TRS_AE_OUT"]=TRS_AE
db["ASR_AE_OUT"]=ASR_AE

# # Transfert de couche
# ICI
db.sync()
db.close()