TensorFlow Machine Learning
Guide AI agents to effectively use TensorFlow for machine learning tasks, model development, training, and deployment.
Overview
TensorFlow is an open-source machine learning framework developed by Google Brain. It provides a flexible architecture for numerical computation and supports deployment across CPUs, GPUs, TPUs, and various platforms from desktops to mobile devices.
Instructions
When working with TensorFlow, follow these guidelines:
1. Installation and Setup
Install TensorFlow using pip: `pip install tensorflow`Verify installation by checking version: `import tensorflow as tf; print(tf.__version__)`For GPU support, ensure CUDA and cuDNN are properly configuredConsider using virtual environments to isolate dependencies2. Basic Workflow
Import TensorFlow: `import tensorflow as tf`Define model architecture using Keras API (`tf.keras`) for high-level operationsPrepare data using `tf.data` API for efficient data pipelinesCompile model with optimizer, loss function, and metricsTrain model using `.fit()` method with training dataEvaluate performance on validation/test setsSave and load models using `model.save()` and `tf.keras.models.load_model()`3. Model Development Best Practices
Start with Sequential API for simple linear stacks of layersUse Functional API for complex architectures with multiple inputs/outputsImplement custom layers by subclassing `tf.keras.layers.Layer`Use callbacks for monitoring, early stopping, and checkpointingLeverage transfer learning with pre-trained models from `tf.keras.applications`Implement data augmentation for improved generalization4. Performance Optimization
Use `tf.data` for efficient input pipelines with prefetching and cachingEnable mixed precision training with `tf.keras.mixed_precision` for faster computationDistribute training across multiple GPUs using `tf.distribute.Strategy`Profile model performance using TensorBoardBatch predictions for efficient inferenceUse TensorFlow Lite for mobile and edge deployment5. Debugging and Monitoring
Enable eager execution for immediate operation evaluation during developmentUse TensorBoard for visualization of training metrics, model graphs, and profilingImplement logging with `tf.print()` for debugging tensor valuesUse `tf.debugging` assertions to validate tensor shapes and valuesMonitor GPU utilization and memory usage6. Common Use Cases
**Image Classification**: Use CNNs with `tf.keras.layers.Conv2D`**Natural Language Processing**: Implement RNNs, LSTMs, or Transformers**Time Series Forecasting**: Use recurrent layers or temporal convolutions**Recommendation Systems**: Build collaborative filtering or content-based models**Object Detection**: Leverage TensorFlow Object Detection API**Generative Models**: Implement GANs or VAEs7. Deployment Considerations
Export models to SavedModel format for serving with TensorFlow ServingConvert to TensorFlow Lite for mobile and embedded devicesUse TensorFlow.js for browser-based deploymentImplement model versioning for production systemsSet up monitoring and logging for deployed modelsExamples
**Simple Neural Network:**
```python
import tensorflow as tf
Define model
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
Compile
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
Train
model.fit(x_train, y_train, epochs=5, validation_split=0.2)
```
**Using tf.data for Data Pipeline:**
```python
dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset = dataset.shuffle(10000).batch(32).prefetch(tf.data.AUTOTUNE)
```
Important Notes
TensorFlow 2.x uses eager execution by default, making debugging easierThe Keras API is the recommended high-level interfaceTensorFlow supports automatic differentiation via `tf.GradientTape`Licensed under Apache 2.0, free for commercial and research useExtensive community support and documentation available at tensorflow.orgCompatible with Python 3.9-3.12 (verify version compatibility for your Python version)