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_layers_lambda.py 7.3 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import unittest
  5. import numpy as np
  6. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
  7. import tensorflow as tf
  8. import tensorlayer as tl
  9. from tests.utils import CustomTestCase
  10. class Layer_Lambda_Test(CustomTestCase):
  11. @classmethod
  12. def setUpClass(cls):
  13. cls.data_x = np.random.random([100, 1]).astype(np.float32)
  14. cls.data_y = cls.data_x**3 + np.random.random() * cls.data_x**2 + np.random.random() * cls.data_x
  15. @classmethod
  16. def tearDownClass(cls):
  17. pass
  18. def test_lambda_keras(self):
  19. layers = [
  20. tf.keras.layers.Dense(10, activation=tf.nn.relu),
  21. tf.keras.layers.Dense(5, activation=tf.nn.sigmoid),
  22. tf.keras.layers.Dense(1, activation=tf.identity)
  23. ]
  24. perceptron = tf.keras.Sequential(layers)
  25. # in order to get trainable_variables of keras
  26. _ = perceptron(np.random.random([100, 5]).astype(np.float32))
  27. class CustomizeModel(tl.layers.Module):
  28. def __init__(self):
  29. super(CustomizeModel, self).__init__()
  30. self.dense = tl.layers.Dense(in_channels=1, n_units=5)
  31. self.lambdalayer = tl.layers.Lambda(perceptron, perceptron.trainable_variables)
  32. def forward(self, x):
  33. z = self.dense(x)
  34. z = self.lambdalayer(z)
  35. return z
  36. optimizer = tf.optimizers.Adam(learning_rate=0.1)
  37. model = CustomizeModel()
  38. print(model.lambdalayer)
  39. model.set_train()
  40. for epoch in range(10):
  41. with tf.GradientTape() as tape:
  42. pred_y = model(self.data_x)
  43. loss = tl.cost.mean_squared_error(pred_y, self.data_y)
  44. gradients = tape.gradient(loss, model.trainable_weights)
  45. optimizer.apply_gradients(zip(gradients, model.trainable_weights))
  46. print("epoch %d, loss %f" % (epoch, loss))
  47. def test_lambda_func_with_args(self):
  48. def customize_func(x, foo=42):
  49. if foo == 0:
  50. return tf.nn.relu(x)
  51. elif foo == 1:
  52. return tf.nn.sigmoid(x)
  53. else:
  54. return tf.identity(x)
  55. class CustomizeModel(tl.layers.Module):
  56. def __init__(self):
  57. super(CustomizeModel, self).__init__()
  58. self.dense = tl.layers.Dense(in_channels=1, n_units=5)
  59. self.lambdalayer = tl.layers.Lambda(customize_func, fn_weights=[], fn_args={'foo': 0})
  60. def forward(self, x, bar):
  61. z = self.dense(x)
  62. if bar == -1:
  63. zf = self.lambdalayer(z)
  64. else:
  65. zf = self.lambdalayer(z, foo=bar)
  66. return z, zf
  67. model = CustomizeModel()
  68. print(model.lambdalayer)
  69. model.set_train()
  70. out, out2 = model(self.data_x, bar=-1)
  71. self.assertTrue(np.array_equal(out2.numpy(), tf.nn.relu(out).numpy()))
  72. out, out2 = model(self.data_x, bar=0)
  73. self.assertTrue(np.array_equal(out2.numpy(), tf.nn.relu(out).numpy()))
  74. out, out2 = model(self.data_x, bar=1)
  75. self.assertTrue(np.array_equal(out2.numpy(), tf.nn.sigmoid(out).numpy()))
  76. out, out2 = model(self.data_x, bar=2)
  77. self.assertTrue(np.array_equal(out2.numpy(), out.numpy()))
  78. def test_lambda_func_with_weight(self):
  79. a = tf.Variable(1.0)
  80. def customize_fn(x):
  81. return x + a
  82. class CustomizeModel(tl.layers.Module):
  83. def __init__(self):
  84. super(CustomizeModel, self).__init__()
  85. self.dense = tl.layers.Dense(in_channels=1, n_units=5)
  86. self.lambdalayer = tl.layers.Lambda(customize_fn, fn_weights=[a])
  87. def forward(self, x):
  88. z = self.dense(x)
  89. z = self.lambdalayer(z)
  90. return z
  91. model = CustomizeModel()
  92. print(model.lambdalayer)
  93. model.set_train()
  94. out = model(self.data_x)
  95. print(out.shape)
  96. def test_lambda_func_without_args(self):
  97. class CustomizeModel(tl.layers.Module):
  98. def __init__(self):
  99. super(CustomizeModel, self).__init__()
  100. self.dense = tl.layers.Dense(in_channels=1, n_units=5)
  101. self.lambdalayer = tl.layers.Lambda(lambda x: 2 * x)
  102. def forward(self, x):
  103. z = self.dense(x)
  104. zf = self.lambdalayer(z)
  105. return z, zf
  106. model = CustomizeModel()
  107. print(model.lambdalayer)
  108. model.set_train()
  109. out, out2 = model(self.data_x)
  110. self.assertTrue(np.array_equal(out2.numpy(), out.numpy() * 2))
  111. def test_elementwiselambda_func_with_args(self):
  112. def customize_func(noise, mean, std, foo=42):
  113. return mean + noise * tf.exp(std * 0.5) + foo
  114. class CustomizeModel(tl.layers.Module):
  115. def __init__(self):
  116. super(CustomizeModel, self).__init__()
  117. self.dense1 = tl.layers.Dense(in_channels=1, n_units=5)
  118. self.dense2 = tl.layers.Dense(in_channels=1, n_units=5)
  119. self.dense3 = tl.layers.Dense(in_channels=1, n_units=5)
  120. self.lambdalayer = tl.layers.ElementwiseLambda(customize_func, fn_args={'foo': 1024})
  121. def forward(self, x, bar=None):
  122. noise = self.dense1(x)
  123. mean = self.dense2(x)
  124. std = self.dense3(x)
  125. if bar is None:
  126. out = self.lambdalayer([noise, mean, std])
  127. else:
  128. out = self.lambdalayer([noise, mean, std], foo=bar)
  129. return noise, mean, std, out
  130. model = CustomizeModel()
  131. print(model.lambdalayer)
  132. model.set_train()
  133. noise, mean, std, out = model(self.data_x)
  134. self.assertTrue(np.allclose(out.numpy(), customize_func(noise, mean, std, foo=1024).numpy()))
  135. noise, mean, std, out = model(self.data_x, bar=2048)
  136. self.assertTrue(np.allclose(out.numpy(), customize_func(noise, mean, std, foo=2048).numpy()))
  137. def test_elementwiselambda_func_without_args(self):
  138. def customize_func(noise, mean, std):
  139. return mean + noise * tf.exp(std * 0.5)
  140. class CustomizeModel(tl.layers.Module):
  141. def __init__(self):
  142. super(CustomizeModel, self).__init__()
  143. self.dense1 = tl.layers.Dense(in_channels=1, n_units=5)
  144. self.dense2 = tl.layers.Dense(in_channels=1, n_units=5)
  145. self.dense3 = tl.layers.Dense(in_channels=1, n_units=5)
  146. self.lambdalayer = tl.layers.ElementwiseLambda(customize_func, fn_weights=[])
  147. def forward(self, x):
  148. noise = self.dense1(x)
  149. mean = self.dense2(x)
  150. std = self.dense3(x)
  151. out = self.lambdalayer([noise, mean, std])
  152. return noise, mean, std, out
  153. model = CustomizeModel()
  154. print(model.lambdalayer)
  155. model.set_train()
  156. noise, mean, std, out = model(self.data_x)
  157. self.assertTrue(np.array_equal(out.numpy(), customize_func(noise, mean, std).numpy()))
  158. if __name__ == '__main__':
  159. unittest.main()

TensorLayer3.0 是一款兼容多种深度学习框架为计算后端的深度学习库。计划兼容TensorFlow, Pytorch, MindSpore, Paddle.