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.

test_auto_monad_layer.py 3.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright 2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. from tqdm import tqdm
  16. import numpy as np
  17. import mindspore as ms
  18. import mindspore.nn as nn
  19. from mindspore.dataset import NumpySlicesDataset
  20. from mindspore import context, Tensor
  21. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  22. class AutoEncoderTrainNetwork(nn.Cell):
  23. def __init__(self):
  24. super(AutoEncoderTrainNetwork, self).__init__()
  25. self.loss_fun = nn.MSELoss()
  26. self.net = nn.CellList([nn.Dense(2, 32), nn.Dense(32, 2)])
  27. self.relu = nn.ReLU()
  28. def reconstruct_sample(self, x: Tensor):
  29. for _, layer in enumerate(self.net):
  30. x = layer(x)
  31. x = self.relu(x)
  32. return x
  33. def construct(self, x: Tensor):
  34. recon_x = self.reconstruct_sample(x)
  35. return self.loss_fun(recon_x, x)
  36. def sample_2d_data(self, n_normals=2000, n_outliers=400):
  37. z = np.random.randn(n_normals, 2)
  38. outliers = np.random.uniform(low=-6, high=6, size=(n_outliers, 2))
  39. centers = np.array([(2., 0), (-2., 0)])
  40. sigma = 0.3
  41. normal_points = sigma * z + centers[np.random.randint(len(centers), size=(n_normals,))]
  42. return np.vstack((normal_points, outliers))
  43. def create_synthetic_dataset(self):
  44. transformed_dataset = self.sample_2d_data()
  45. for dim in range(transformed_dataset.shape[1]):
  46. min_val = transformed_dataset[:, dim].min()
  47. max_val = transformed_dataset[:, dim].max()
  48. if min_val != max_val:
  49. transformed_dataset[:, dim] = (transformed_dataset[:, dim] - min_val) / (max_val - min_val)
  50. elif min_val != 1:
  51. transformed_dataset[:, dim] = transformed_dataset[:, dim] / min_val
  52. transformed_dataset = transformed_dataset.astype(np.float32)
  53. return transformed_dataset
  54. def test_auto_monad_layer():
  55. ae_with_loss = AutoEncoderTrainNetwork()
  56. transformed_dataset = ae_with_loss.create_synthetic_dataset()
  57. dataloader = NumpySlicesDataset(data=(transformed_dataset,), shuffle=True)
  58. dataloader = dataloader.batch(batch_size=16)
  59. optim = nn.RMSProp(params=ae_with_loss.trainable_params(), learning_rate=0.002,)
  60. train_net = nn.TrainOneStepCell(ae_with_loss, optim)
  61. train_net.set_train()
  62. gen_samples = dict()
  63. num_epoch = 21
  64. for epoch in tqdm(range(num_epoch)):
  65. loss = []
  66. for _, (batch,) in enumerate(dataloader):
  67. batch = Tensor(batch, dtype=ms.float32)
  68. loss_ = train_net(batch)
  69. loss.append(loss_.asnumpy())
  70. avg_loss = np.array(loss).mean()
  71. if epoch % 10 == 0:
  72. gen_samples[epoch] = ae_with_loss.reconstruct_sample(Tensor(transformed_dataset)).asnumpy()
  73. print(f"epoch: {epoch}/{num_epoch}, avg loss: {avg_loss}")