This code trains a small neural network on the XOR problem and shows how loss and accuracy change over 20 epochs. It also prints the final accuracy.
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
# Prepare simple data: XOR problem
x_train = [[0,0],[0,1],[1,0],[1,1]]
y_train = [0,1,1,0]
# Build a small model
model = models.Sequential([
layers.Dense(4, activation='relu', input_shape=(2,)),
layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train model and save history
history = model.fit(x_train, y_train, epochs=20, verbose=0)
# Plot loss and accuracy
plt.figure(figsize=(10,4))
plt.subplot(1,2,1)
plt.plot(history.history['loss'], label='loss')
plt.title('Training Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['accuracy'], label='accuracy')
plt.title('Training Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.show()
# Print final accuracy
final_acc = history.history['accuracy'][-1]
print(f'Final training accuracy: {final_acc:.2f}')