help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
tensorflow-deeplearning
/
src
RSK World
tensorflow-deeplearning
Deep learning with TensorFlow and Keras
src
  • utils
  • __init__.py330 B
  • autoencoders.py8 KB
  • cnns.py6.7 KB
  • custom_layers.py8.3 KB
  • data_generator.py14.2 KB
  • data_preprocessing.py9.9 KB
  • gans.py7 KB
  • model_deployment.py8.7 KB
  • model_evaluation.py10.5 KB
  • model_training.py10.1 KB
  • neural_networks.py4.7 KB
  • rnns.py6.8 KB
  • transfer_learning.py5.4 KB
  • transformers.py7.8 KB
  • visualization.py9.6 KB
econometric_data.csvREADME.mdlazy_evaluation.pyadvanced_queries.pyhypothesis_testing_example.pycustom_layers.py
README.md
Raw Download

README.md

# TensorFlow Deep Learning

<!--
Project: TensorFlow Deep Learning
Author: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
Category: Deep Learning
Difficulty: Advanced
-->

Deep learning with TensorFlow including neural networks, CNNs, RNNs, and building custom models for various applications.

## Description

This project provides a comprehensive guide to TensorFlow, Google's deep learning framework. It covers neural network construction, convolutional neural networks (CNNs), recurrent neural networks (RNNs), custom layers, model training, and deployment. Perfect for building deep learning applications.

## Features

### Core Deep Learning Models
- **Neural Networks**: Feedforward networks, deep networks with batch normalization
- **CNNs**: Simple CNNs, deep CNNs, ResNet-style architectures
- **RNNs**: Simple RNN, LSTM, GRU, Bidirectional LSTM, Sequence-to-sequence models
- **Transformers**: Multi-head attention, encoder-decoder architectures
- **Transfer Learning**: Pre-trained models (VGG16, ResNet50, MobileNet, InceptionV3, etc.)
- **GANs**: Generative Adversarial Networks (DCGAN implementation)
- **Autoencoders**: Simple, Convolutional, and Variational Autoencoders

### Advanced Features
- **Custom Layers**: Custom dense, attention, and residual layers
- **Model Training**: Advanced training techniques, callbacks, data augmentation, mixed precision
- **Model Evaluation**: Comprehensive metrics, confusion matrices, ROC curves
- **Data Preprocessing**: Image, text, and tabular data preprocessing pipelines
- **Visualization**: Training history, model architecture, feature importance, layer activations
- **Model Deployment**: SavedModel, H5, TFLite, TensorFlow.js, REST API
- **Docker Support**: Containerized deployment with Docker and Docker Compose

## Technologies

- **Deep Learning**: TensorFlow, Keras
- **Data Processing**: NumPy, Pandas, Scikit-learn
- **Visualization**: Matplotlib, Seaborn
- **Development**: Jupyter Notebook, Python 3.8+
- **Deployment**: Flask, Docker, TensorFlow Serving
- **Utilities**: Pillow, TensorFlow.js

## Project Structure

```
tensorflow-deeplearning/
├── README.md
├── requirements.txt
├── setup.py
├── main.py
├── config.yaml
├── env.example
├── Dockerfile
├── docker-compose.yml
├── notebooks/
│ ├── 01_neural_networks.ipynb
│ ├── 02_cnns.ipynb
│ ├── 03_rnns.ipynb
│ └── 04_custom_models.ipynb
├── src/
│ ├── __init__.py
│ ├── neural_networks.py
│ ├── cnns.py
│ ├── rnns.py
│ ├── transformers.py
│ ├── transfer_learning.py
│ ├── gans.py
│ ├── autoencoders.py
│ ├── custom_layers.py
│ ├── model_training.py
│ ├── model_deployment.py
│ ├── model_evaluation.py
│ ├── data_preprocessing.py
│ ├── visualization.py
│ └── utils/
│ ├── __init__.py
│ └── helpers.py
├── api/
│ ├── server.py
│ └── requirements.txt
├── examples/
│ ├── train_custom_model.py
│ └── transfer_learning_example.py
├── tests/
│ ├── test_neural_networks.py
│ └── test_cnns.py
├── models/
│ └── .gitkeep
└── data/
└── .gitkeep
```

## Installation

1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```

## Installation

1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. (Optional) For API server:
```bash
pip install -r api/requirements.txt
```

## Usage

### Running Python Scripts

```bash
# Using main entry point
python main.py --module neural_networks
python main.py --module cnns
python main.py --module rnns
python main.py --module transfer_learning
python main.py --module gans
python main.py --module autoencoders

# Direct module execution
python src/neural_networks.py
python src/cnns.py
python src/rnns.py
```

### Running Example Scripts

```bash
python examples/train_custom_model.py
python examples/transfer_learning_example.py
```

### Running Jupyter Notebooks

```bash
jupyter notebook notebooks/
```

### Running Tests

```bash
python -m pytest tests/
# or
python -m unittest discover tests
```

### Running API Server

```bash
# Using Python directly
python api/server.py

# Using Docker
docker-compose up tensorflow-api

# The API will be available at http://localhost:5000
```

### Docker Deployment

```bash
# Build and run with Docker Compose
docker-compose up -d

# Run Jupyter notebook in Docker
docker-compose up jupyter
```

## API Endpoints

- `GET /health` - Health check
- `POST /predict` - Single prediction
- `POST /predict/batch` - Batch predictions
- `GET /model/info` - Model information

## Configuration

Edit `config.yaml` or create `.env` file from `env.example` to customize settings.

## Contact

**RSK World**
- Website: https://rskworld.in
- Email: help@rskworld.in
- Phone: +91 93305 39277

## License

This project is for educational purposes.
src/custom_layers.py
Raw Download
Find: Go to:
"""
Custom Layers and Models with TensorFlow
Author: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277

This module demonstrates how to create custom layers and models in TensorFlow/Keras.
"""

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, Model
import numpy as np

class DenseLayer(layers.Layer):
    """
    Custom dense layer with custom initialization.
    Author: RSK World - https://rskworld.in
    """
    
    def __init__(self, units, activation=None, **kwargs):
        super(DenseLayer, self).__init__(**kwargs)
        self.units = units
        self.activation = keras.activations.get(activation)
    
    def build(self, input_shape):
        self.kernel = self.add_weight(
            name='kernel',
            shape=(input_shape[-1], self.units),
            initializer='glorot_uniform',
            trainable=True
        )
        self.bias = self.add_weight(
            name='bias',
            shape=(self.units,),
            initializer='zeros',
            trainable=True
        )
        super(DenseLayer, self).build(input_shape)
    
    def call(self, inputs):
        output = tf.matmul(inputs, self.kernel) + self.bias
        if self.activation is not None:
            output = self.activation(output)
        return output
    
    def get_config(self):
        config = super(DenseLayer, self).get_config()
        config.update({
            'units': self.units,
            'activation': keras.activations.serialize(self.activation)
        })
        return config

class AttentionLayer(layers.Layer):
    """
    Custom attention layer for sequence models.
    Author: RSK World - https://rskworld.in
    """
    
    def __init__(self, units, **kwargs):
        super(AttentionLayer, self).__init__(**kwargs)
        self.units = units
    
    def build(self, input_shape):
        self.W1 = self.add_weight(
            name='W1',
            shape=(input_shape[-1], self.units),
            initializer='glorot_uniform',
            trainable=True
        )
        self.W2 = self.add_weight(
            name='W2',
            shape=(self.units, 1),
            initializer='glorot_uniform',
            trainable=True
        )
        super(AttentionLayer, self).build(input_shape)
    
    def call(self, inputs):
        # Compute attention scores
        attention_scores = tf.matmul(tf.tanh(tf.matmul(inputs, self.W1)), self.W2)
        attention_weights = tf.nn.softmax(attention_scores, axis=1)
        
        # Apply attention weights
        context = tf.reduce_sum(attention_weights * inputs, axis=1)
        return context
    
    def get_config(self):
        config = super(AttentionLayer, self).get_config()
        config.update({'units': self.units})
        return config

class ResidualBlock(layers.Layer):
    """
    Custom residual block layer.
    Author: RSK World - https://rskworld.in
    """
    
    def __init__(self, units, **kwargs):
        super(ResidualBlock, self).__init__(**kwargs)
        self.units = units
    
    def build(self, input_shape):
        self.dense1 = layers.Dense(self.units, activation='relu')
        self.bn1 = layers.BatchNormalization()
        self.dense2 = layers.Dense(self.units)
        self.bn2 = layers.BatchNormalization()
        
        # Shortcut connection
        if input_shape[-1] != self.units:
            self.shortcut = layers.Dense(self.units)
        else:
            self.shortcut = lambda x: x
        
        super(ResidualBlock, self).build(input_shape)
    
    def call(self, inputs, training=False):
        # Main path
        x = self.dense1(inputs)
        x = self.bn1(x, training=training)
        x = self.dense2(x)
        x = self.bn2(x, training=training)
        
        # Shortcut connection
        shortcut = self.shortcut(inputs)
        
        # Add and activate
        output = layers.Activation('relu')(x + shortcut)
        return output
    
    def get_config(self):
        config = super(ResidualBlock, self).get_config()
        config.update({'units': self.units})
        return config

class CustomCNNModel(Model):
    """
    Custom CNN model using functional API.
    Author: RSK World - https://rskworld.in
    """
    
    def __init__(self, num_classes=10, **kwargs):
        super(CustomCNNModel, self).__init__(**kwargs)
        
        # Convolutional layers
        self.conv1 = layers.Conv2D(32, 3, activation='relu')
        self.bn1 = layers.BatchNormalization()
        self.pool1 = layers.MaxPooling2D(2)
        
        self.conv2 = layers.Conv2D(64, 3, activation='relu')
        self.bn2 = layers.BatchNormalization()
        self.pool2 = layers.MaxPooling2D(2)
        
        self.conv3 = layers.Conv2D(128, 3, activation='relu')
        self.bn3 = layers.BatchNormalization()
        self.pool3 = layers.MaxPooling2D(2)
        
        # Dense layers
        self.flatten = layers.Flatten()
        self.dense1 = layers.Dense(256, activation='relu')
        self.dropout = layers.Dropout(0.5)
        self.dense2 = layers.Dense(num_classes, activation='softmax')
    
    def call(self, inputs, training=False):
        x = self.conv1(inputs)
        x = self.bn1(x, training=training)
        x = self.pool1(x)
        
        x = self.conv2(x)
        x = self.bn2(x, training=training)
        x = self.pool2(x)
        
        x = self.conv3(x)
        x = self.bn3(x, training=training)
        x = self.pool3(x)
        
        x = self.flatten(x)
        x = self.dense1(x)
        x = self.dropout(x, training=training)
        return self.dense2(x)

class CustomRNNModel(Model):
    """
    Custom RNN model with attention mechanism.
    Author: RSK World - https://rskworld.in
    """
    
    def __init__(self, vocab_size, embedding_dim=128, lstm_units=256, num_classes=10, **kwargs):
        super(CustomRNNModel, self).__init__(**kwargs)
        
        self.embedding = layers.Embedding(vocab_size, embedding_dim)
        self.lstm1 = layers.LSTM(lstm_units, return_sequences=True)
        self.lstm2 = layers.LSTM(lstm_units, return_sequences=True)
        self.attention = AttentionLayer(units=128)
        self.dense1 = layers.Dense(128, activation='relu')
        self.dropout = layers.Dropout(0.5)
        self.dense2 = layers.Dense(num_classes, activation='softmax')
    
    def call(self, inputs, training=False):
        x = self.embedding(inputs)
        x = self.lstm1(x)
        x = self.lstm2(x)
        x = self.attention(x)
        x = self.dense1(x)
        x = self.dropout(x, training=training)
        return self.dense2(x)

def create_model_with_custom_layers(input_shape, num_classes):
    """
    Create a model using custom layers.
    
    Args:
        input_shape: Shape of input data
        num_classes: Number of output classes
    
    Returns:
        Compiled Keras model
    """
    inputs = keras.Input(shape=input_shape)
    
    # Use custom dense layer
    x = DenseLayer(128, activation='relu')(inputs)
    x = layers.Dropout(0.2)(x)
    
    # Use residual block
    x = ResidualBlock(64)(x)
    x = ResidualBlock(32)(x)
    
    # Output layer
    outputs = layers.Dense(num_classes, activation='softmax')(x)
    
    model = keras.Model(inputs, outputs)
    
    model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy']
    )
    
    return model

def example_usage():
    """
    Example usage of custom layers and models.
    """
    # Generate sample data
    X_train = np.random.randn(1000, 784).astype('float32')
    y_train = np.random.randint(0, 10, 1000)
    
    # Create model with custom layers
    model = create_model_with_custom_layers(input_shape=(784,), num_classes=10)
    
    # Display model architecture
    model.summary()
    
    # Train model
    model.fit(
        X_train, y_train,
        batch_size=32,
        epochs=5,
        verbose=1
    )
    
    return model

if __name__ == '__main__':
    print("Custom Layers and Models with TensorFlow")
    print("Author: RSK World - https://rskworld.in")
    model = example_usage()
272 lines•8.3 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer