WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TensorFlow · Basic · question 10 of 100

How can you implement a simple Neural Network using TensorFlow?

📕 Buy this interview preparation book: 100 TensorFlow questions & answers — PDF + EPUB for $5

Here’s an example of how to implement a simple neural network using TensorFlow:

    import tensorflow as tf
    import numpy as np
    
    # Define the input data and labels
    X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32)
    y = np.array([[0], [1], [1], [0]], dtype=np.float32)
    
    # Define the layers of the network
    input_layer = tf.keras.layers.Input(shape=(2,))
    hidden_layer = tf.keras.layers.Dense(units=4, activation=tf.nn.relu)(input_layer)
    output_layer = tf.keras.layers.Dense(units=1, activation=tf.nn.sigmoid)(hidden_layer)
    
    # Define the model and compile it
    model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer)
    model.compile(optimizer=tf.optimizers.Adam(), loss=tf.losses.binary_crossentropy, metrics=['accuracy'])
    
    # Train the model
    model.fit(X, y, epochs=1000)
    
    # Make a prediction using the trained model
    prediction = model.predict(np.array([[0, 1]]))
    print(prediction)  # [[0.999]]

In this example, we define a simple neural network with one hidden layer and one output layer. The input layer has two units, corresponding to the two features in the input data. The hidden layer has four units and uses the ReLU activation function. The output layer has one unit and uses the sigmoid activation function.

We then define the model and compile it using the Adam optimizer and binary crossentropy loss function. We train the model for 1000 epochs using the input data and labels, and then make a prediction using the trained model on a new input.

This is just a simple example, and neural networks can become much more complex with many layers, activation functions, and other advanced features. However, the basic principles remain the same, and TensorFlow provides a powerful and flexible platform for building and training neural networks for a wide range of machine learning tasks.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TensorFlow interview — then scores it.
📞 Practice TensorFlow — free 15 min
📕 Buy this interview preparation book: 100 TensorFlow questions & answers — PDF + EPUB for $5

All 100 TensorFlow questions · All topics