element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Forum Can anyone help me solve this error I am getting
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • Replies 1 reply
  • Subscribers 45 subscribers
  • Views 1243 views
  • Users 0 members are here
  • tensorflow
Related

Can anyone help me solve this error I am getting

manojroy123
manojroy123 11 months ago

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, LeakyReLU, concatenate

def tiny_yolo_v2(input_shape, num_classes):
    inputs = Input(shape=input_shape)

    # Tiny YOLOv2 architecture
    x = Conv2D(16, (3, 3), padding='same')(inputs)
    x = BatchNormalization()(x)
    x = LeakyReLU(alpha=0.1)(x)

    x = Conv2D(32, (3, 3), strides=(2, 2), padding='same')(x)
    x = BatchNormalization()(x)
    x = LeakyReLU(alpha=0.1)(x)

    x = Conv2D(64, (3, 3), strides=(2, 2), padding='same')(x)
    x = BatchNormalization()(x)
    x = LeakyReLU(alpha=0.1)(x)

    x = Conv2D(128, (3, 3), strides=(2, 2), padding='same')(x)
    x = BatchNormalization()(x)
    x = LeakyReLU(alpha=0.1)(x)

    x = Conv2D(256, (3, 3), strides=(2, 2), padding='same')(x)
    x = BatchNormalization()(x)
    x = LeakyReLU(alpha=0.1)(x)

    # Final output layer
    x = Conv2D(num_classes, (1, 1), padding='same')(x)

    model = Model(inputs, x)
    return model

def load_darknet_weights(model, weights_file):
    with open(weights_file, "rb") as f:
        header = np.fromfile(f, dtype=np.int32, count=5)  # Read header
        weights = np.fromfile(f, dtype=np.float32)  # Read weights

    layer_index = 0
    for layer in model.layers:
        if isinstance(layer, Conv2D):
            filters = layer.filters
            kernel_size = layer.kernel_size[0]
            input_dim = layer.input_shape[-1]
            
            # Load weights
            if layer.use_bias:
                start = layer_index * (filters * (kernel_size ** 2) * input_dim + filters)
            else:
                start = layer_index * (filters * (kernel_size ** 2) * input_dim)

            end = start + (filters * (kernel_size ** 2) * input_dim)
            kernel = weights[start:end].reshape((kernel_size, kernel_size, input_dim, filters))
            layer.set_weights([kernel])
            
            
            if layer.use_bias:
                start = end
                end = start + filters
                bias = weights[start:end]
                layer.set_weights([kernel, bias])

            layer_index += 1

# Specify parameters
input_shape = (416, 416, 3)
num_classes = 20  # Adjust based on your dataset

# Create the Tiny YOLOv2 model
model = tiny_yolo_v2(input_shape, num_classes)

# Load weights from Darknet
weights_file = 'yolov2-tiny.weights'  # Path to your weights file
load_darknet_weights(model, weights_file)

# Save the model in H5 format
model.save('tiny_yolo_v2.h5')

print("Model saved to 'tiny_yolo_v2.h5'")

I am getting this error

> %Run 'file reading.py'
2024-10-10 14:42:55.306715: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2024-10-10 14:43:07.741864: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
C:\Users\manojroy\AppData\Roaming\Python\Python310\site-packages\keras\src\layers\activations\leaky_relu.py:41: UserWarning: Argument `alpha` is deprecated. Use `negative_slope` instead.
warnings.warn(
Traceback (most recent call last):
File "C:\Users\manojroy\Desktop\CircuitDigest\AssistiveTechForBlind\Yolo2Tiny\file reading.py", line 76, in <module>
load_darknet_weights(model, weights_file)
File "C:\Users\manojroy\Desktop\CircuitDigest\AssistiveTechForBlind\Yolo2Tiny\file reading.py", line 46, in load_darknet_weights
input_dim = layer.input_shape[-1]
AttributeError: 'Conv2D' object has no attribute 'input_shape'

the code is for convertion of yolov2 tiny weights to tensorflow *.h5 weights. If some one has any better solutions please let me know about it.

  • Sign in to reply
  • Cancel

Top Replies

  • bidrohini
    bidrohini 11 months ago +1
    Edit your code like this and try: import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, LeakyReLU…
  • bidrohini
    bidrohini 11 months ago

    Edit your code like this and try:

    import numpy as np
    import tensorflow as tf
    from tensorflow.keras.models import Model
    from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, LeakyReLU
    
    def tiny_yolo_v2(input_shape, num_classes):
        inputs = Input(shape=input_shape)
    
        # Tiny YOLOv2 architecture
        x = Conv2D(16, (3, 3), padding='same', use_bias=False)(inputs)
        x = BatchNormalization()(x)
        x = LeakyReLU(negative_slope=0.1)(x)
    
        x = Conv2D(32, (3, 3), strides=(2, 2), padding='same', use_bias=False)(x)
        x = BatchNormalization()(x)
        x = LeakyReLU(negative_slope=0.1)(x)
    
        x = Conv2D(64, (3, 3), strides=(2, 2), padding='same', use_bias=False)(x)
        x = BatchNormalization()(x)
        x = LeakyReLU(negative_slope=0.1)(x)
    
        x = Conv2D(128, (3, 3), strides=(2, 2), padding='same', use_bias=False)(x)
        x = BatchNormalization()(x)
        x = LeakyReLU(negative_slope=0.1)(x)
    
        x = Conv2D(256, (3, 3), strides=(2, 2), padding='same', use_bias=False)(x)
        x = BatchNormalization()(x)
        x = LeakyReLU(negative_slope=0.1)(x)
    
        # Final output layer
        x = Conv2D(num_classes, (1, 1), padding='same', use_bias=True)(x)
    
        model = Model(inputs, x)
        return model
    
    def load_darknet_weights(model, weights_file):
        with open(weights_file, "rb") as f:
            header = np.fromfile(f, dtype=np.int32, count=5)  # Read header
            weights = np.fromfile(f, dtype=np.float32)  # Read weights
    
        ptr = 0  # Pointer to track the current position in weights array
    
        for layer in model.layers:
            if isinstance(layer, Conv2D):
                # Get the number of filters, kernel size, and input dimensions
                filters = layer.filters
                kernel_size = layer.kernel_size[0]
                input_dim = layer.input.shape[-1]
    
                # Calculate the size of the kernel weights
                kernel_weights_size = filters * input_dim * kernel_size * kernel_size
                # Extract kernel weights and reshape
                kernel_weights = weights[ptr:ptr + kernel_weights_size]
                kernel_weights = kernel_weights.reshape((kernel_size, kernel_size, input_dim, filters))
                ptr += kernel_weights_size
    
                if layer.use_bias:
                    # If the layer has bias, load them
                    bias_weights = weights[ptr:ptr + filters]
                    ptr += filters
                    layer.set_weights([kernel_weights, bias_weights])
                else:
                    # If the layer doesn't use bias, it likely has BatchNorm
                    # Load BatchNorm parameters: [gamma, beta, mean, variance]
                    bn_layer = model.layers[model.layers.index(layer) + 1]
                    if isinstance(bn_layer, BatchNormalization):
                        bn_weights = weights[ptr:ptr + 4 * filters]
                        gamma = bn_weights[0:filters]
                        beta = bn_weights[filters:2 * filters]
                        mean = bn_weights[2 * filters:3 * filters]
                        variance = bn_weights[3 * filters:4 * filters]
                        bn_layer.set_weights([gamma, beta, mean, variance])
                        ptr += 4 * filters
    
    # Specify parameters
    input_shape = (416, 416, 3)
    num_classes = 20  # Adjust based on your dataset
    
    # Create the Tiny YOLOv2 model
    model = tiny_yolo_v2(input_shape, num_classes)
    
    # Load weights from Darknet
    weights_file = 'yolov2-tiny.weights'  # Path to your weights file
    load_darknet_weights(model, weights_file)
    
    # Save the model in H5 format
    model.save('tiny_yolo_v2.h5')
    
    print("Model saved to 'tiny_yolo_v2.h5'")
    

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube