导入错误“没有名为‘keras.legacy_tf_layers’的模块”

问题描述 投票:0回答:1

`有人可以帮我解决此代码中的错误吗? 还有另一个错误,任何尝试运行此代码的人都会看到它会是tensorflow.keras.python.datautils 的导入错误,类似的问题,要解决这个问题,只需进入内置的tensorflow,从tensorflow.keras 中删除.python 部分。 python.datautils 输入文件只是视频中的帧

import cv2
import numpy as np
#import tensorflow as tf
import tensorflow.compat.v1 as tf
import tensornets as nets
from tensornets.utils import load_img
import math
import scipy.io as sio
import time
import random
import itertools
import os
from pprint import pprint
import pickle
import glob
from sklearn.preprocessing import StandardScaler
from sklearn import preprocessing
from keras.models import Sequential
from keras.layers import AveragePooling3D

tf.compat.v1.disable_eager_execution()

batch_size = 32
seg_size = 32
dims = [batch_size, 224, 224, 3]
no_of_videos = 950
global flags


def generate_feat(inputx, model, out_feats, sess):
    """Use the imgload that comes with the model to read the image of each video
    Then use the model to process these images to get the output characteristics
    Finally save these features as a file in npy format
    """
    # Import video list
    global flags
    seg_name = os.path.basename(flags.input)
    vid_names = glob.glob(os.path.join(flags.input, '*'))
    res_feats = np.zeros([no_of_videos, seg_size, 2048], np.float32)
    # Read seg_size pictures evenly for each video, and process one video as a batch
    for idx, vid_n in enumerate(vid_names):
        # Read in all the picture names of the video and select seg_size pictures evenly
        input_imgs = np.zeros(shape=dims, dtype=np.float32)
        vid_idx = int(os.path.basename(vid_n)[:])
        fpaths = glob.glob(os.path.join(vid_n, '*'))
        frm_len = len(fpaths)
        if frm_len == 0:
            continue
        delta = frm_len / seg_size
        idx_list = [int(i*delta) for i in range(seg_size)]
        print(idx, vid_n, frm_len, max(idx_list))
        # Use load_img to read the images in the list, and model.preprocess for preprocessing
        for idx2, idx3 in enumerate(idx_list):
            img_path = fpaths[idx3]
            img = load_img(img_path, target_size=256, crop_size=224)
            input_imgs[idx2,:,:,:] = model.preprocess(img)

        feats = sess.run(out_feats, {inputx: input_imgs})

        res_feats[vid_idx] = feats
        print(idx, 'video has been processed.')
    np.save(flags.output, res_feats)

    res_feats = res_feats.reshape(1, no_of_videos, 32, 2048, 1)
    model = Sequential([AveragePooling3D(pool_size = (1, 32, 1))])
    resnet_avg = model.predict(res_feats)
    resnet_avg = np.squeeze(resnet_avg)

    min_max_scaler = preprocessing.MinMaxScaler()
    scaled_resnet = min_max_scaler.fit_transform(resnet_avg.reshape(-1,no_of_videos))
    scaled_resnet = scaled_resnet.reshape(no_of_videos,-1)
    np.save(flags.scaled_output, scaled_resnet)


if __name__ == "__main__":
    global flags
    #Directory address to read the frames
    tf.app.flags.DEFINE_string('input', '/content/drive/MyDrive/Frames', 'input path')
    #Address where npy file has to be saved
    tf.app.flags.DEFINE_string('output', '/content/drive/MyDrive/ResNeXt', 'output path')
    tf.app.flags.DEFINE_string('scaled_output', '/content/drive/MyDrive/Scaled_ResNeXt',    'scaled output path')
    flags = tf.app.flags.FLAGS
    # Model file
    inputx = tf.placeholder(tf.float32, [None, 224, 224, 3])
    model = nets.ResNeXt101c64(inputx, is_training=False)
    out_feats = model.get_outputs()[-3]
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    sess.run(tf.global_variables_initializer())
    sess.run(model.pretrained())
    # Feature
    generate_feat(inputx, model, out_feats, sess)

输出

/usr/local/lib/python3.10/dist-packages/tensorflow/python/keras      /engine/base_layer_v1.py:1697: UserWarning: `layer.apply` is   deprecated and will be removed in a future version. Please use `layer.__call__` method instead.
warnings.warn('`layer.apply` is deprecated and '

---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

<ipython-input-1-d9504b4a8959> in <cell line: 82>()
     90     # Model file
     91     inputx = tf.placeholder(tf.float32, [None, 224, 224, 3])
---> 92     model = nets.ResNeXt101c64(inputx, is_training=False)
     93     out_feats = model.get_outputs()[-3]
     94     config = tf.ConfigProto()

17 frames

/usr/local/lib/python3.10/dist-packages/tensornets/utils.py in  wrapper(*args, **kwargs)
    272             reuse = kwargs.get('reuse', None)
    273             with tf.variable_scope(scope, reuse=reuse):
--> 274                 x = func(*args, **kwargs)
    275                 if func.__name__ == 'wrapper':
    276                     from .middles import direct as p0

/usr/local/lib/python3.10/dist-packages/tensornets/utils.py in wrapper(*args, **kwargs)
    354             with arg_scope(layers, outputs_collections=__outputs__):
    355                 with arg_scopes(layers_args):
--> 356                     x = func(*args, **kwargs)
    357                     x.model_name = func.__name__
    358                     return x

/usr/local/lib/python3.10/dist-packages/tensornets/resnets.py in resnext101c64(x, is_training, classes, stem, scope, reuse)
    227         x = _stack(x, _block3c64, 2048, 3, scope='conv5')
    228         return x
--> 229     return resnet(x, False, stack_fn, is_training, classes, stem, scope, reuse)
    230 
    231 

/usr/local/lib/python3.10/dist-packages/tensornets/resnets.py in   resnet(x, preact, stack_fn, is_training, classes, stem, scope, reuse)
     70         x = conv2d(x, 64, 7, stride=2, scope='conv1')
     71     else:
---> 72         x = conv(x, 64, 7, stride=2, scope='conv1')
     73         x = relu(x, name='conv1/relu')
     74     x = pad(x, pad_info(0 if stem else 3, symmetry=not preact),

/usr/local/lib/python3.10/dist-packages/tensornets/layers.py in convbn(*args, **kwargs)
     51     scope = kwargs.pop('scope', None)
     52     with tf.variable_scope(scope):  
---> 53         return batch_norm(conv2d(*args, **kwargs))
     54 
     55 

/usr/local/lib/python3.10/dist-packages/tensornets   /contrib_framework/arg_scope.py in func_with_args(*args, **kwargs)
    180       current_args = current_scope[key_func].copy()
    181       current_args.update(kwargs)
--> 182     return func(*args, **current_args)
    183 
    184   _add_op(func)

/usr/local/lib/python3.10/dist-packages/tensornets  /contrib_layers/layers.py in batch_norm(inputs, decay, center, scale, epsilon, activation_fn, param_initializers, param_regularizers, updates_collections, is_training, reuse, variables_collections, outputs_collections, trainable, batch_weights, fused, data_format, zero_debias_moving_mean, scope, renorm, renorm_clipping, renorm_decay, adjustment)
    627       beta_regularizer = param_regularizers.get('beta')
    628       gamma_regularizer = param_regularizers.get('gamma')
--> 629       layer = normalization_layers.BatchNormalization(
    630           axis=axis,
    631           momentum=decay,

/usr/local/lib/python3.10/dist-packages/tensorflow/python/layers/normalization.py in __getattr__(name)
     28 def __getattr__(name):
     29   if name in ['BatchNormalization', 'BatchNorm']:
---> 30     return normalization.BatchNormalization
     31   elif name in ['batch_normalization', 'batch_norm']:
     32     return normalization.batch_normalization

/usr/local/lib/python3.10/dist-packages/tensorflow/python/util/lazy_loader.py in __getattr__(self, item)
     64 
     65   def __getattr__(self, item):
---> 66     module = self._load()
     67     return getattr(module, item)
     68 

/usr/local/lib/python3.10/dist-packages/tensorflow/python/util/lazy_loader.py in _load(self)
     47     """Load the module and insert it into the parent's globals."""
     48     # Import the target module and insert it into the parent's namespace
---> 49     module = importlib.import_module(self.__name__)
     50     self._parent_module_globals[self._local_name] = module
     51 

/usr/lib/python3.10/importlib/__init__.py in import_module(name, package)
    124                 break
    125             level += 1
--> 126     return _bootstrap._gcd_import(name[level:], package, level)
    127 
    128 

/usr/lib/python3.10/importlib/_bootstrap.py in _gcd_import(name, package, level)

/usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load(name, import_)

/usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

/usr/lib/python3.10/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

/usr/lib/python3.10/importlib/_bootstrap.py in _gcd_import(name, package, level)

/usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load(name, import_)

/usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

ModuleNotFoundError: No module named 'keras.legacy_tf_layers'

我尝试查看库以查找 keras.legacy_tf_layers 的导入或使用发生在哪里,但没有找到任何内容。 我尝试更新tensorflow和keras但没有用。

tensorflow import
1个回答
0
投票

这可能是由于您安装的 tensorflow 版本所致。尝试做:

pip install --upgrade "tensorflow<=2.10"

您可以在此处阅读有关此主题的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.