First, make sure TensorFlow is installed in your Python environment:
pip install tensorflow
This command installs TensorFlow and all its dependencies.
Start your Python script or Jupyter notebook by importing TensorFlow:
import tensorflow as tf
You can use the high-level Keras API to define a model. Keras is integrated into TensorFlow and makes it easy to define and train deep learning models.
Here’s how to define a simple Sequential model:
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(input_feature_count,)),
tf.keras.layers.Dense(1)
])
Before training the model, you need to compile it with an optimizer, a loss function, and metrics to evaluate:
model.compile(
optimizer='adam',
loss='mean_squared_error',
metrics=['accuracy']
)
Use the fit
method to train the model with training data:
model.fit(x_train, y_train, epochs=10)
After training, evaluate the model with test data or use it to make predictions:
loss, accuracy = model.evaluate(x_test, y_test)
predictions = model.predict(x_new)
If you need more control, TensorFlow offers:
model.fit()
, you can write your own training loops for more flexibility.tf.data
API.You can save the entire model or just the weights:
model.save('my_model.h5') # Saves the model
model = tf.keras.models.load_model('my_model.h5') # Loads the model
Use pre-trained models from TensorFlow Hub:
import tensorflow_hub as hub
model = tf.keras.Sequential([
hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/4",
input_shape=(224,224,3), trainable=False),
tf.keras.layers.Dense(num_classes, activation='softmax')
])
For more detailed tutorials, API documentation, and practical examples, visit the TensorFlow website and explore the TensorFlow tutorials. These resources provide comprehensive guides on using TensorFlow APIs across various applications and use cases.