You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

paddle_model.py 2.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from fastNLP.envs.imports import _NEED_IMPORT_PADDLE
  2. if _NEED_IMPORT_PADDLE:
  3. import paddle
  4. import paddle.nn as nn
  5. class PaddleNormalModel_Classification_1(paddle.nn.Layer):
  6. """
  7. 基础的paddle分类模型
  8. """
  9. def __init__(self, num_labels, feature_dimension):
  10. super(PaddleNormalModel_Classification_1, self).__init__()
  11. self.num_labels = num_labels
  12. self.linear1 = nn.Linear(in_features=feature_dimension, out_features=64)
  13. self.ac1 = nn.ReLU()
  14. self.linear2 = nn.Linear(in_features=64, out_features=32)
  15. self.ac2 = nn.ReLU()
  16. self.output = nn.Linear(in_features=32, out_features=num_labels)
  17. self.loss_fn = nn.CrossEntropyLoss()
  18. def forward(self, x):
  19. x = self.ac1(self.linear1(x))
  20. x = self.ac2(self.linear2(x))
  21. x = self.output(x)
  22. return x
  23. def train_step(self, x, y):
  24. x = self(x)
  25. return {"loss": self.loss_fn(x, y)}
  26. def evaluate_step(self, x, y):
  27. x = self(x)
  28. return {"pred": x, "target": y.reshape((-1,))}
  29. class PaddleNormalModel_Classification_2(paddle.nn.Layer):
  30. """
  31. 基础的paddle分类模型,只实现 forward 函数测试用户自己初始化了分布式的场景
  32. """
  33. def __init__(self, num_labels, feature_dimension):
  34. super(PaddleNormalModel_Classification_2, self).__init__()
  35. self.num_labels = num_labels
  36. self.linear1 = nn.Linear(in_features=feature_dimension, out_features=64)
  37. self.ac1 = nn.ReLU()
  38. self.linear2 = nn.Linear(in_features=64, out_features=32)
  39. self.ac2 = nn.ReLU()
  40. self.output = nn.Linear(in_features=32, out_features=num_labels)
  41. self.loss_fn = nn.CrossEntropyLoss()
  42. def forward(self, x, y):
  43. x = self.ac1(self.linear1(x))
  44. x = self.ac2(self.linear2(x))
  45. x = self.output(x)
  46. loss = self.loss_fn(x, y)
  47. return {"loss": self.loss_fn(x, y), "pred": x, "target": y.reshape((-1,))}