Python 属性错误:';密集型';对象没有属性';内核&x27;尝试在线程中运行TensorFlow模型推断时

Python 属性错误:';密集型';对象没有属性';内核&x27;尝试在线程中运行TensorFlow模型推断时,python,multithreading,tensorflow,machine-learning,fastapi,Python,Multithreading,Tensorflow,Machine Learning,Fastapi,我正在为一个项目实现一个变体 到目前为止,我已经设法让它工作。模型为输入图像输出一个标题。到目前为止没有错误。这是工作代码: @app.post('/api/uploadFile') async def upload_file(file: UploadFile = Form(...)): if file.content_type.startswith('image/'): filepath = f'./static/uploads/{file.filename}'

我正在为一个项目实现一个变体

到目前为止,我已经设法让它工作。模型为输入图像输出一个标题。到目前为止没有错误。这是工作代码:

@app.post('/api/uploadFile')
async def upload_file(file: UploadFile = Form(...)):
    if file.content_type.startswith('image/'):
        filepath = f'./static/uploads/{file.filename}'
        with open(filepath, 'wb') as buffer:
            copyfileobj(file.file, buffer)
        print(generate_caption(filepath)) # Calls image captioning model
        print(detect_labels(filepath, config['detect_func'], config['cat_idx'])) # Calls object detection model. detect_func and cat_idx are initialised at server startup
        print('done')
    return {
        'uploadSuccess': True
    }

def generate_caption(image):
    try:
        hidden = decoder.reset_state(batch_size=1)
    except:
        hidden = decoder.layers[-1].reset_state(batch_size=1)

    img_tensor_val = tf.expand_dims(decode_image(image), 0)
    features = encoder(img_tensor_val)
    dec_input = tf.expand_dims([tokenizer.word_index['<start>']], 0)
    result = list()

    for i in range(MAX_LEN):
        predictions, hidden, _ = decoder(dec_input, features, hidden)
        predicted_id = tf.random.categorical(predictions, 1)[0][0].numpy()
        result.append(tokenizer.index_word[predicted_id])
        if tokenizer.index_word[predicted_id] == '<end>':
            break
        dec_input = tf.expand_dims([predicted_id], 0)

    return ' '.join(
        [word for word in result
         if word != '<start>' and word != '<end>' and word != '<unk>'])

def detect_labels(img_path: str, detect_fn, category_index):
    img_np = load_image(img_path)
    input_tensor = convert_to_tensor(np.expand_dims(img_np, 0), dtype=float32)
    detections, _, _ = detect_fn(input_tensor)

    classes = (detections['detection_classes'][0].numpy() + 1).astype(int)
    scores = detections['detection_scores'][0].numpy()
    labels = {category_index[classes[i]]['name']
              for i in range(scores.shape[0]) if scores[i] > 0.3}

    return labels
当我运行这段代码并上传5幅图像时,前2幅图像被解析得很好。但是,接下来的3个图像会抛出以下内容:

AttributeError:“稠密”对象没有属性“内核”

知道怎么了吗

@app.post('/api/uploadFile')
async def upload_file(file: UploadFile = Form(...)):
    if file.content_type.startswith('image/'):
        filepath = f'./static/uploads/{file.filename}'
        with open(filepath, 'wb') as buffer:
            copyfileobj(file.file, buffer)
            thread = Thread(target=annotate_image, name=f'{filepath}_annotation_thread', args=[filepath])
            thread.start()
    return {
        'uploadSuccess': True
    }

def annotate_image(filepath: str):
    print(f'Starting {filepath}_annotation_thread')
    print(generate_caption(filepath))
    print(detect_labels(filepath, config['detect_func'], config['cat_idx']))
    print(f'{filepath} done')