Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

inference.py 1.9 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  1. import os
  2. import sys
  3. import json
  4. import yaml
  5. import torch
  6. import importlib
  7. import numpy as np
  8. import pandas as pd
  9. from tqdm import tqdm
  10. from pathlib import Path
  11. from data_loader.data_loaders import DataFrameDataLoader
  12. from dotenv import load_dotenv
  13. load_dotenv('envs/.env')
  14. with open('params.yaml', 'r') as f:
  15. PARAMS = yaml.safe_load(f)
  16. config_path = Path(os.getenv('OUTPUT_PATH'), os.getenv('CONFIG_PATH'))
  17. with open(config_path, 'r') as f:
  18. CONFIG = json.load(f)
  19. def inference(method='lstm'):
  20. try:
  21. model_module = importlib.import_module(f'model.{method}')
  22. model = model_module.Model(**CONFIG, **PARAMS[method])
  23. except Exception as e:
  24. raise e
  25. model_path = Path(os.getenv('OUTPUT_PATH'), f'{sys.argv[1]}_{os.getenv("MODEL_PATH")}')
  26. model.load_model(model_path)
  27. if torch.cuda.is_available():
  28. device = torch.device('cuda', PARAMS.get('gpu', 0))
  29. else:
  30. device = torch.device('cpu')
  31. model.to(device)
  32. df = pd.read_csv('data/test.csv')
  33. df[PARAMS['label']] = 0
  34. with torch.no_grad():
  35. all_preds = list()
  36. inference_dataloader = DataFrameDataLoader(
  37. df, batch_size=PARAMS['evaluate']['batch_size'], use_bag=PARAMS[method]['use_bag'],
  38. use_eos=PARAMS[method].get('use_eos'), max_len=PARAMS[method].get('max_len')
  39. )
  40. for idx, (label, text, offsets) in enumerate(tqdm(inference_dataloader)):
  41. predicted_label = model(text, offsets)
  42. predicted_label = (predicted_label > 0.5).squeeze(dim=-1)
  43. all_preds += [predicted_label.detach().cpu().numpy().astype(int)]
  44. all_preds = np.concatenate(all_preds, axis=0)
  45. df[PARAMS['label']] = all_preds
  46. return df
  47. if __name__ == '__main__':
  48. method = sys.argv[1]
  49. df = inference(method)
  50. df = df[['ID', PARAMS['label']]]
  51. submission_path = Path(os.getenv('OUTPUT_PATH'), f'{method}_{os.getenv("SUBMISSION_PATH")}')
  52. df.to_csv(submission_path, index=False)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...