Ass9(Neural Network)

 # Step 1: Import libraries 

import numpy as np 

from tensorflow.keras.models import Sequential 

from tensorflow.keras.layers import Dense 

from tensorflow.keras.optimizers import Adam 

# Step 2: Define XOR data 

X = np.array([[0, 0], 

              [0, 1], 

              [1, 0], 

              [1, 1]]) 

y = np.array([[0], 

              [1], 

              [1], 

              [0]]) 

# Step 3: Build the model 

model = Sequential() 

model.add(Dense(4, input_dim=2, activation='relu'))  # Hidden layer with 4 neurons 

model.add(Dense(1, activation='sigmoid'))            # Output layer 

# Step 4: Compile the model 

model.compile(optimizer=Adam(learning_rate=0.1), loss='binary_crossentropy', 

metrics=['accuracy']) 

# Step 5: Train the model 

model.fit(X, y, epochs=500, verbose=0) 

# Step 6: Evaluate and Predict 

predictions = model.predict(X).round() 

print("\n    XOR Predictions:") 

for i in range(len(X)): 

    print(f"Input: {X[i]} -> Predicted Output: {int(predictions[i][0])}")

Comments