Spaces:
Sleeping
Sleeping
Download src/loader.py from duvr/sentiment_analysis: direct link, hf CLI and curl.
- Browser
- Download file 5.55 kB
-
https://huggingface.co/spaces/duvr/sentiment_analysis/resolve/b798b9052d474ffb7798dea55620eac0e71dfef1/src/loader.py
- Command line
-
hf download hf://spaces/duvr/sentiment_analysis@b798b9052d474ffb7798dea55620eac0e71dfef1/src/loader.py
-
curl -L -o loader.py https://huggingface.co/spaces/duvr/sentiment_analysis/resolve/b798b9052d474ffb7798dea55620eac0e71dfef1/src/loader.py
5.55 kB
| import os | |
| import joblib | |
| import torch | |
| from src.config import langs_dir, models_name | |
| cwd = os.getcwd() | |
| class ModelArgs: | |
| input_size: int | |
| hidden_size: int # rnn | |
| num_layers: int = 1 # rnn | |
| hidden_layers: list # mlp | |
| output_size: int | |
| nonlinearity: str = "tanh" # 'tanh' | 'relu' | |
| dropout: int = 0 | |
| class MLPClassifier: | |
| def __init__(self, model): | |
| self.model = model # MLPModelCustom() | |
| def predict(self, x: torch.Tensor): | |
| self.model.eval() | |
| with torch.torch.no_grad(): # no calcular gradiente | |
| output = self.model(x) # (batch_size, output_size) | |
| pred = torch.nn.functional.softmax(output, dim=1).squeeze() | |
| return [torch.argmax(pred).tolist()] | |
| class RNNClassifier: | |
| def __init__(self, base_model): | |
| self.model = base_model # MLPModelCustom() | |
| def predict(self, x: torch.Tensor, length): | |
| self.model.eval() # Desactiva Dropout | |
| with torch.torch.no_grad(): # no calcular gradiente | |
| output = self.model(x, length) # (batch_size, output_size) | |
| pred = torch.nn.functional.softmax(output, dim=1).squeeze() | |
| return [torch.argmax(pred).tolist()] | |
| es_model_args = ModelArgs() | |
| es_model_args.hidden_layers = [128, 64] | |
| es_model_args.hidden_size = 128 | |
| es_model_args.num_layers = 2 | |
| es_model_args.output_size = 3 | |
| es_model_args.dropout = 0.20 | |
| en_model_args = ModelArgs() | |
| en_model_args.hidden_layers = [128, 64] | |
| en_model_args.hidden_size = 128 | |
| en_model_args.num_layers = 2 | |
| en_model_args.output_size = 3 | |
| en_model_args.dropout = 0.20 | |
| model_args = {"es": es_model_args, "en": en_model_args} | |
| def get_model(lang, model_name, embedding_model=None): | |
| dir_name = langs_dir[lang] | |
| model_path = models_name[model_name] | |
| path = os.path.join(cwd, dir_name, model_path) | |
| if model_name in {"SVM", "NB", "LR", "SWEM"}: | |
| return joblib.load(path) | |
| device = "cpu" | |
| args = model_args[lang] | |
| args.input_size = embedding_model.vector_size() | |
| if model_name == "MLP": | |
| model = MLPModelCustom(args) | |
| state_dict = torch.load(path, map_location=device) | |
| # model.load_state_dict(state_dict) | |
| model.load_state_dict(state_dict["model_state_dict"]) | |
| return MLPClassifier(model) | |
| if model_name == "RNN": | |
| model = RNNModel(args) | |
| state_dict = torch.load(path, map_location=device) | |
| # model.load_state_dict(state_dict) | |
| model.load_state_dict(state_dict["model_state_dict"]) | |
| return RNNClassifier(model) | |
| if model_name == "LSTM": | |
| model = LSTMModel(args) | |
| state_dict = torch.load(path, map_location=device) | |
| # model.load_state_dict(state_dict) | |
| model.load_state_dict(state_dict["model_state_dict"]) | |
| return RNNClassifier(model) | |
| class MLPModelCustom(torch.nn.Module): | |
| def __init__(self, model_args): | |
| super().__init__() | |
| layers = [] | |
| previous_dim = model_args.input_size | |
| for hidden_dim in model_args.hidden_layers: | |
| layers.append(torch.nn.Linear(previous_dim, hidden_dim)) | |
| layers.append(torch.nn.ReLU()) | |
| layers.append(torch.nn.Dropout(model_args.dropout)) | |
| previous_dim = hidden_dim | |
| layers.append(torch.nn.Linear(previous_dim, model_args.output_size)) | |
| self.network = torch.nn.Sequential(*layers) | |
| def forward(self, x): | |
| return self.network(x) | |
| class RNNModel(torch.nn.Module): | |
| def __init__(self, model_args: ModelArgs): | |
| super().__init__() | |
| self.rnn = torch.nn.RNN( | |
| input_size=model_args.input_size, # Número de características por palabra | Tamaño de los embeddings | |
| hidden_size=model_args.hidden_size, # Número de características/neuronas de la capa recurrente | |
| num_layers=model_args.num_layers, # Núumero de capas recurrentes | |
| nonlinearity=model_args.nonlinearity, # 'relu' deafult: 'tanh' | |
| dropout=model_args.dropout, # Porcentaje de neuronas desactivadas durante el entrenamiento | |
| batch_first=True, # Los tensores de entrada y salida tienen las dimensiones (batch, seq, feature) | |
| ) | |
| self.fc = torch.nn.Linear( | |
| model_args.hidden_size, # Número de características de entrada | |
| model_args.output_size, # Número de clases | |
| ) | |
| def forward(self, x, lengths): | |
| packed_x = torch.nn.utils.rnn.pack_padded_sequence( | |
| x, lengths, batch_first=True, enforce_sorted=False | |
| ) | |
| packed_output, hidden = self.rnn(packed_x) | |
| h_n = hidden[-1] # tomar la salida de la última capa rnn | |
| return self.fc(h_n) | |
| class LSTMModel(torch.nn.Module): | |
| def __init__(self, model_args: ModelArgs): | |
| super().__init__() | |
| self.lstm = torch.nn.LSTM( | |
| input_size=model_args.input_size, | |
| hidden_size=model_args.hidden_size, | |
| num_layers=model_args.num_layers, | |
| dropout=model_args.dropout, | |
| batch_first=True, | |
| ) | |
| self.fc = torch.nn.Linear( | |
| in_features=model_args.hidden_size, out_features=model_args.output_size | |
| ) | |
| def forward(self, x, lengths): | |
| packed_input_sequences = torch.nn.utils.rnn.pack_padded_sequence( | |
| x, lengths, batch_first=True, enforce_sorted=False | |
| ) | |
| packed_output_sequences, (hidden, cell) = self.lstm(packed_input_sequences) | |
| h_n = hidden[-1] # Tomar el estado oculto final de la última capa | |
| return self.fc(h_n) # (batch_size, output_size) | |