scnets.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. from keras import backend as K
  2. from keras.models import Sequential, Model
  3. from keras.layers import Dense, Dropout
  4. from keras.layers import Reshape, UpSampling1D, Conv1D
  5. from keras.layers import Flatten, Activation
  6. from keras.utils import np_utils, multi_gpu_model
  7. from keras.regularizers import l2
  8. from keras.wrappers.scikit_learn import KerasRegressor
  9. from keras.optimizers import Adam
  10. import numpy as np
  11. import matplotlib.pyplot as plt
  12. from keras.layers import PReLU
  13. #function to test performance on testset
  14. def calc_mre(y_true, y_pred):
  15. y_err = 100*np.abs(y_true - y_pred)/y_true
  16. return np.mean(y_err)
  17. #function to test performance on testset
  18. def calc_mre_K(y_true, y_pred):
  19. y_err = 100*np.abs(y_true - y_pred)/y_true
  20. return K.mean(y_err)
  21. #naive percentage loss
  22. def relerr_loss(y_true, y_pred):
  23. y_err = np.abs(y_true - y_pred)/y_true
  24. y_err_f = K.flatten(y_err)
  25. return K.sum(y_err_f)
  26. def conv1dmodel(in_size=8,
  27. out_size=256,
  28. c1_nf=64,
  29. clayers=2,
  30. ker_size=3):
  31. # create model
  32. model = Sequential()
  33. model.add(Dense(out_size, input_dim=in_size,
  34. kernel_initializer='normal',
  35. name='first', activation='relu' ))
  36. model.add(Reshape((4, 64), name='Reshape1'))
  37. model.add(UpSampling1D(size=2, name='Up1'))
  38. model.add(Conv1D(filters=c1_nf,
  39. kernel_size=ker_size, strides=1, padding='same',
  40. dilation_rate=1, name='Conv1',
  41. kernel_initializer='normal', activation='relu'))
  42. for cl in np.arange(clayers):
  43. model.add(Conv1D(filters=32,
  44. kernel_size=ker_size,
  45. strides=1,
  46. padding='same',
  47. dilation_rate=1,
  48. name='Conv'+ str(cl+2),
  49. kernel_initializer='normal',
  50. activation='relu'))
  51. model.add(Flatten())
  52. model.compile(loss=relerr_loss, optimizer='adam', metrics=[calc_mre_K])
  53. return model
  54. def convprel(in_size=8,
  55. out_size=256,
  56. c1_nf=64,
  57. clayers=2,
  58. ker_size=3):
  59. # create model
  60. model = Sequential()
  61. model.add(Dense(out_size, input_dim=in_size,
  62. kernel_initializer='normal',
  63. name='first'))
  64. model.add(PReLU(alpha_initializer='zeros', alpha_regularizer=None))
  65. model.add(Reshape((4, 64), name='Reshape1'))
  66. model.add(UpSampling1D(size=2, name='Up1'))
  67. model.add(Conv1D(filters=c1_nf,
  68. kernel_size=ker_size, strides=1, padding='same',
  69. dilation_rate=1, name='Conv1',
  70. kernel_initializer='normal'))
  71. model.add(PReLU(alpha_initializer='zeros', alpha_regularizer=None))
  72. for cl in np.arange(clayers):
  73. model.add(Conv1D(filters=32,
  74. kernel_size=ker_size,
  75. strides=1,
  76. padding='same',
  77. dilation_rate=1,
  78. name='Conv'+ str(cl+2),
  79. kernel_initializer='normal'))
  80. model.add(PReLU(alpha_initializer='zeros', alpha_regularizer=None))
  81. model.add(Flatten())
  82. model.compile(loss=relerr_loss, optimizer='adam', metrics=[calc_mre_K])
  83. return model
  84. def fullycon( in_size=8, out_size=250, N_hidden=3, N_neurons=250, N_gpus=1):
  85. """
  86. Returns a fully-connected model which will take a normalized size vector and return a
  87. spectrum
  88. in_size: length of the size vector
  89. out_size: length of the spectrum vector
  90. N_hidden: number of hidden layers
  91. N_neurons: number of neurons in each of the hidden layers
  92. """
  93. model = Sequential()
  94. model.add(Dense(out_size, input_dim=in_size, kernel_initializer='normal', activation='relu',
  95. name='first' ))
  96. for h in np.arange(N_hidden):
  97. lname = "H"+str(h)
  98. model.add(Dense(out_size, kernel_initializer='normal', activation='relu', name=lname ))
  99. model.add(Dense(out_size, kernel_initializer='normal', name='last'))
  100. # Compile model
  101. if N_gpus == 1:
  102. model.compile(loss=relerr_loss, optimizer='adam', metrics=[calc_mre_K])
  103. else:
  104. gpu_list = ["gpu(%d)" % i for i in range(N_gpus)]
  105. model.compile(loss=relerr_loss, optimizer='adam', metrics=[calc_mre_K], context = gpu_list)
  106. return model
  107. #staging area for new models
  108. def plot_training_history(history, red_factor):
  109. loss, val_loss = history.history['loss'], history.history['val_loss']
  110. loss = np.asarray(loss)/red_factor
  111. val_loss = np.asarray(val_loss)/red_factor
  112. epochs = len(loss)
  113. fig, axs = plt.subplots(1,1, figsize=(5,5))
  114. axs.semilogy(np.arange(1, epochs + 1), loss, label='train error')
  115. axs.semilogy(np.arange(1, epochs + 1), val_loss, label='validation error')
  116. axs.set_xlabel('Epoch number')
  117. axs.set_ylabel('Mean Relative Error (MRE) (%)')
  118. axs.legend(loc="best")