9951 explained code solutions for 126 technologies


python-tensorflowHow do I use Python TensorFlow.Keras.Models to create a machine learning model?


Python TensorFlow.Keras.Models can be used to create a machine learning model. To do this, the following steps can be taken:

  1. First, import the relevant libraries:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
  1. Then, create the model structure by defining the layers:
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
  1. Compile the model, specifying the optimizer, loss function and metrics:
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
  1. Fit the model to the training data for a specified number of epochs:
model.fit(train_data, train_targets, epochs=5)
  1. Evaluate the model on the test data:
test_loss, test_acc = model.evaluate(test_data, test_targets)
  1. Make predictions using the model:
predictions = model.predict(test_data)
  1. Finally, save the model for future use:
model.save('my_model.h5')

Helpful links

Edit this code on GitHub