Search code examples
tensorflowkerassequentialnonlinear-optimization

Tensorflow keras Sequential model for math problem


i want to make a model to predict the side of Right angle triangle , i gives two input (Length of two sides of Right angle triangle ) and want to predict third side of the triangle.


Solution

  • Here is a code for a simple regression problem, right angle triangle in this case.

    from tensorflow import keras
    import tensorflow as tf
    import numpy as np
    
    a=np.array([3,2,3,4,7,10,11,13,14,20])  #side a
    b=np.array([4,5,6,9,8,11,12,14,16,42])  #side b
    h=np.sqrt(a**2+b**2)       #hypotenuse side (creating ground truth dataset using sides a and b)
    x=np.stack((a, b), axis=-1)
    print(f'input: {x}')
    print(f'output: {h}')
    
    
    model=keras.Sequential([
      keras.layers.Dense(4,activation=keras.activations.relu,input_shape=[2]),
      keras.layers.Dense(2,activation=keras.activations.relu),
      keras.layers.Dense(1)
    ])
    optimizer = tf.keras.optimizers.RMSprop(0.1)
    model.compile(optimizer=tf.keras.optimizers.Adam(0.11),
                 loss=tf.keras.losses.mean_squared_error)
    

    Train the model.

    model.fit(x,h, epochs=15)
    

    Predict.

    model.predict([[3,4]])
    

    Output: array([[5.0573754]], dtype=float32)