This program trains a small model on dummy data, saves it, loads it back, and makes a prediction on new data.
import tensorflow as tf
import numpy as np
# Create and train a simple model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential([
Dense(10, activation='relu', input_shape=(4,)),
Dense(3, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Dummy data: 5 samples, 4 features each
x_train = np.array([
[5.1, 3.5, 1.4, 0.2],
[6.2, 3.4, 5.4, 2.3],
[5.9, 3.0, 4.2, 1.5],
[6.9, 3.1, 5.1, 2.3],
[5.5, 2.3, 4.0, 1.3]
])
# Labels for 3 classes
y_train = np.array([0, 2, 1, 2, 1])
# Train briefly
model.fit(x_train, y_train, epochs=3, verbose=1)
# Save the model
model.save('my_simple_model')
# Load the model
loaded_model = tf.keras.models.load_model('my_simple_model')
# New data for inference
x_new = np.array([[6.0, 3.0, 4.8, 1.8]])
# Predict
predictions = loaded_model.predict(x_new)
print('Predictions:', predictions)
# Show predicted class
predicted_class = predictions.argmax(axis=1)
print('Predicted class:', predicted_class[0])