Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. import tensorflow as tf
  2. from tensorflow import keras
  3. from tensorflow.keras.layers import *
  4. from tensorflow.keras.models import Model
  5. from tensorflow.keras import backend as K
  6.  
  7. BINSIZE = 1
  8. XMIN = 0
  9.  
  10. def weighted_avg(inputs):
  11. # Calculate weighted sum of inputs
  12. ones = K.ones_like(inputs[0,:]) # [1, 1, 1, 1....] (size Nouts)
  13. idx = K.cumsum(ones) # [1, 2, 3, 4....] (size Nouts)
  14. norm = K.sum(inputs, axis=-1, keepdims=True) # normalization of all outputs by batch. shape is 1D array of size batch
  15. wavg = K.sum(idx*inputs, axis=-1, keepdims=True)/norm # array of size batch with weighted avg. of mean in units of bins
  16. wavg_cm = wavg*BINSIZE + XMIN # array of size batch with weighted avg. of mean in physical units
  17.  
  18. return wavg_cm
  19.  
  20. def make_model():
  21. inp = Input(shape=(4,))
  22. out = Lambda(weighted_avg)(inp)
  23. model = Model(inp, out)
  24. model.compile('adam', 'mse')
  25. return model
  26.  
  27. model = make_model()
  28. model.summary()
  29.  
  30. import numpy as np
  31. X = np.array([
  32. [1, 1, 1, 1],
  33. [1, 0, 0, 0],
  34. [0, 1, 0, 0],
  35. [0, 0, 1, 0],
  36. [0, 0, 0, 1]
  37. ])
  38. model.predict(X)
  39.  
  40. array([[2.5],
  41. [1. ],
  42. [2. ],
  43. [3. ],
  44. [4. ]], dtype=float32)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement