layer.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import * as tf from '@tensorflow/tfjs'
  2. type Shape = tf.Shape
  3. export type LayerType =
  4. | 'conv2d'
  5. | 'maxPooling2d'
  6. | 'flatten'
  7. | 'dense'
  8. | 'averagePooling2d'
  9. type ActivationType = 'tanh' | 'sigmoid' | 'softmax' | 'relu'
  10. export const activations: ActivationType[] = ['tanh', 'sigmoid', 'softmax', 'relu']
  11. export abstract class Layer {
  12. layerName: string
  13. layerType: LayerType
  14. static conv2dLayer() {
  15. return new Conv2dLayer()
  16. }
  17. static maxPooling2dLayer() {
  18. return new PoolingLayer('max pooling 2d layer', 'maxPooling2d')
  19. }
  20. static averagePooling2dLayer() {
  21. return new PoolingLayer('average pooling 2d layer', 'averagePooling2d')
  22. }
  23. static flattenLayer() {
  24. return new FalttenLayer()
  25. }
  26. static denseLayer() {
  27. return new DensLayer()
  28. }
  29. protected constructor(
  30. layerName: string,
  31. layerType: LayerType
  32. ) {
  33. this.layerName = layerName
  34. this.layerType = layerType
  35. }
  36. abstract toTfLayer(inputShape?: Shape): tf.layers.Layer
  37. }
  38. class Conv2dLayer extends Layer {
  39. filters: number = 32
  40. kernelSize: number = 3
  41. activation: ActivationType = 'sigmoid'
  42. constructor() {
  43. super('conv2d layer', 'conv2d')
  44. }
  45. toTfLayer(inputShape?: Shape) {
  46. return tf.layers.conv2d({
  47. filters: this.filters,
  48. kernelSize: this.kernelSize,
  49. activation: this.activation,
  50. inputShape
  51. })
  52. }
  53. }
  54. class FalttenLayer extends Layer {
  55. constructor() {
  56. super('flatten layer', 'flatten')
  57. }
  58. toTfLayer(inputShape?: Shape) {
  59. return tf.layers.flatten({ inputShape })
  60. }
  61. }
  62. class PoolingLayer extends Layer {
  63. poolsize: number = 2
  64. strides: number = 2
  65. toTfLayer(inputShape?: Shape) {
  66. if (this.layerType === 'maxPooling2d') {
  67. return tf.layers.maxPool2d({
  68. poolSize: this.poolsize,
  69. strides: this.strides,
  70. inputShape
  71. })
  72. } else {
  73. return tf.layers.averagePooling2d({
  74. poolSize: this.poolsize,
  75. strides: this.strides,
  76. inputShape
  77. })
  78. }
  79. }
  80. }
  81. class DensLayer extends Layer {
  82. units: number = 10
  83. activation: ActivationType = 'softmax'
  84. constructor() {
  85. super('dense layer', 'dense')
  86. }
  87. toTfLayer(inputShape?: Shape) {
  88. this.units = Number.parseInt('' + this.units)
  89. return tf.layers.dense({
  90. units: this.units,
  91. activation: this.activation,
  92. inputShape
  93. })
  94. }
  95. }