Guest User

Untitled

a guest
Nov 18th, 2020
83
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import tensorflow
  2. from tensorflow.keras.models import Sequential
  3. from tensorflow.keras.layers import Dense
  4. from tensorflow.keras.losses import binary_crossentropy
  5. from tensorflow.keras.optimizers import Adam
  6. from tensorflow.keras.callbacks import LambdaCallback
  7. import numpy as np
  8.  
  9. # Model configuration
  10. batch_size = 1
  11. no_epochs = 10
  12. verbosity = 2
  13.  
  14. # Array of 6 values
  15. x = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])
  16. y = np.array([0, 1, 0, 1, 0, 1])
  17.  
  18. # DenseAndPrint Layer
  19. # Source before adaptation: https://keras.io/guides/making_new_layers_and_models_via_subclassing/
  20. class DenseAndPrint(tensorflow.keras.layers.Layer):
  21.   def __init__(self, units=32, input_dim=32, activation='linear'):
  22.     super(DenseAndPrint, self).__init__()
  23.     w_init = tensorflow.random_normal_initializer()
  24.     self.w = tensorflow.Variable(
  25.         initial_value=w_init(shape=(input_dim, units), dtype="float32"),
  26.         trainable=True,
  27.     )
  28.     b_init = tensorflow.zeros_initializer()
  29.     self.b = tensorflow.Variable(
  30.         initial_value=b_init(shape=(units,), dtype="float32"), trainable=True
  31.     )
  32.     self.activation = activation
  33.  
  34.   def call(self, inputs):
  35.     tensorflow.print(inputs)
  36.     mult = tensorflow.matmul(inputs, self.w) + self.b
  37.     if self.activation == 'relu':
  38.       return tensorflow.math.maximum(mult, 0)
  39.     else:
  40.       return mult
  41.  
  42. # Create the model
  43. model = Sequential()
  44. model.add(DenseAndPrint(16, activation='relu', input_dim=1))
  45. model.add(Dense(8, activation='relu'))
  46. model.add(Dense(1, activation='sigmoid'))
  47.  
  48. # Compile the model
  49. model.compile(loss=binary_crossentropy,
  50.           optimizer=Adam(),
  51.           metrics=['accuracy'])
  52.  
  53. # Fit data to model
  54. model.fit(x, y,
  55.       batch_size=batch_size,
  56.       epochs=no_epochs,
  57.       verbose=verbosity)
  58.  
RAW Paste Data