import tensorflow as tf
from tensorflow.keras import layers, models
# Load MNIST data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Normalize data
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
# Flatten images
x_train = x_train.reshape(-1, 28*28)
x_test = x_test.reshape(-1, 28*28)
# Build simple model
model = models.Sequential([
layers.Dense(64, activation='relu', input_shape=(28*28,)),
layers.Dense(10, activation='softmax')
])
# Compile model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Print weights before training
print('Weights before training:')
for layer in model.layers:
weights = layer.get_weights()
if weights:
print(weights[0].shape, 'weights sample:', weights[0][0][:5])
# Train model
history = model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1, verbose=2)
# Print weights after training
print('Weights after training:')
for layer in model.layers:
weights = layer.get_weights()
if weights:
print(weights[0].shape, 'weights sample:', weights[0][0][:5])
# Evaluate on test data
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f'Test accuracy after training: {test_acc:.4f}')