Skip to content

Instantly share code, notes, and snippets.

@jshayiding
Created February 19, 2021 20:30
Show Gist options
  • Save jshayiding/6b3fb511a3d1678aeca0a02482fa8167 to your computer and use it in GitHub Desktop.
Save jshayiding/6b3fb511a3d1678aeca0a02482fa8167 to your computer and use it in GitHub Desktop.
## approach-1
#--------------------------------------------------------------------#
def taylor_func(x, func_type='sin(x)', n_terms=2):
# f(a) + 0.5 * f`(a)(x - a) + f``(a)(x - a)^2
if func_type == 'sin(x)':
c = tf.constant([1, -1/6, 1/120, -1/5040], dtype=tf.float32)
p = tf.constant([1,3,5,7], dtype=tf.float32)
if func_type == 'ln(1+x)':
c = tf.constant([1, -1/2, 1/3, -1/4, 1/5, -1/6], dtype=tf.float32)
p = tf.constant([1,2,3,4,5,6], dtype=tf.float32)
new_x = [x] + [i * tf.math.pow(x, j) for i, j in zip(c, p)]
new_x = tf.stack(new_x, axis=-1)
return new_x
#--------------------------------------------------------------------#
## aproach-2
def taylor_expend(x):
c = tf.constant([1, -1/6, 1/120, -1/5040], dtype=tf.float32)
p = tf.constant([1, 3, 5, 7], dtype=tf.float32)
exp = []
def loop(i):
if i > 3:
return
pp = tf.gather(p, i)
cc = tf.gather(c, i)
t = (x ** pp) * cc
exp.append(t)
loop(i + 1)
loop(0)
exp = tf.stack(exp, axis=-1)
return exp
#--------------------------------------------------------------------#
## aproach-3
inputs = tf.keras.Input(shape=(32,32,3))
conv_1 = Conv2D(64, (3, 3), input_shape=(32,32,3), padding='same')(inputs)
BN_1 = BatchNormalization(axis=-1)(conv_1)
pool_1 = MaxPooling2D(strides=(1,1), pool_size=(3,3), padding='same')(BN_1)
PEN_1 = taylor_func(pool_1, func_type="sin(x)", n_terms=2)
PEN_1 = tf.stack([pool_1, - (1/6) * tf.math.pow(pool_1, 3), (1/120) * tf.math.pow(pool_1, 5)], axis=1) ## 3 expansion terms of sin(x)
PEN_1 =tf.reshape(PEN_1, (-1, PEN_1.shape[2], PEN_1.shape[2], PEN_1.shape[1]*PEN_1.shape[-1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment