Skip to content

Instantly share code, notes, and snippets.

@haifengkao
Created October 21, 2020 10:09
Show Gist options
  • Save haifengkao/7c27d7974aff7ae286b8ba6dedf651cb to your computer and use it in GitHub Desktop.
Save haifengkao/7c27d7974aff7ae286b8ba6dedf651cb to your computer and use it in GitHub Desktop.
Can RNN learn that the length of input sequence is even or odd number?
import tensorflow as tf
import random
def genSequence():
len = 101
X = []
for i in range(1, len):
X.append([[random.random()]]*i)
y = []
for i in range(1, len):
if i % 2 == 0:
y.append(1)
else:
y.append(0)
return (X, y)
if __name__ == "__main__":
X, y = genSequence()
XTensor = tf.ragged.constant(X, dtype=tf.float32)
yTensor = tf.ragged.constant(y, dtype=tf.float32)
print(XTensor)
print(yTensor)
# Build the Keras model.
keras_model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(None, 1), dtype=tf.float32, ragged=True),
tf.keras.layers.LSTM(32, use_bias=True),
tf.keras.layers.Dense(1)
])
keras_model.summary()
keras_model.compile(loss='MSE', optimizer=tf.keras.optimizers.Adam(0.001))
keras_model.fit(XTensor, yTensor, epochs=200)
print(keras_model.predict(tf.constant([[[1]]])))
print(keras_model.predict(tf.constant([[[1]]*2])))
print(keras_model.predict(tf.constant([[[1]]*50])))
print(keras_model.predict(tf.constant([[[1]]*51])))
print(keras_model.predict(tf.constant([[[1]]*150])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment