属性错误:模块“tensorflow.security.fuzzing.py.annotation_types”没有属性“Float8e4m3fn”

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

我刚刚收到一条我不明白的错误消息,我在第一次运行后收到此错误消息。因此第一次运行有效,但随后从 Tensorflow 导入失败。在第二次运行时它停止工作。我没有改变任何东西。这是我的 Jupyter Notebook 中的完整代码。我正在尝试制作一个 AI 来玩 GTA。先驾驶,再射击。

我的代码:


# %%
### IMPORTS

## system
import psutil
import os
import sys

## input
import pyautogui
import time
import keyboard
import screeninfo

## AI
import numpy as np
import pandas as pd

import tensorflow as tf ## ERROR Line here
print(tf.__version__)
import tensorflow_hub as hub
print(hub.__version__)

import neat

print("The following GPU devices are available: %s" % tf.test.gpu_device_name())



## Window
import pygetwindow as gw
from src.grabscreen import grab_screen


## C2V
from PIL import Image, ImageGrab # ImageColor, ImageDraw, ImageFont, ImageOps
import cv2
cv2.ocl.setUseOpenCL(True)
import math




# %%
## Var list
DEBUG       = True
crosshair   = (224,224,224)
gta_window  = [i for i in screeninfo.get_monitors() if i.is_primary == True][0]


moule_handle = "https://tfhub.dev/google/openimages_v4/ssd/mobilenet_v2/1" #@param ["https://tfhub.dev/google/openimages_v4/ssd/mobilenet_v2/1", "https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1"]
detector = hub.load(moule_handle).signatures['default']


# %%
## function lib


def is_gta_running():
    return any(process.name() == "GTA5.exe" for process in psutil.process_iter())

input_list = {}
def add_input(func):
    input_list[func.__name__] = func
    return func

def gta_loaded():
    return pyautogui.locateOnScreen("img/story_mode.PNG", confidence=0.7)

def story_mode():
    return pyautogui.locateOnScreen("img/story_mode.PNG", confidence=0.7)

def start_gta():
    pyautogui.press("win")
    pyautogui.write("Grand Theft Auto V")
    pyautogui.press("enter")
    
def click_button(button):
    pyautogui.click(button)
    time.sleep(1)
    pyautogui.mouseDown(button='left')
    time.sleep(1)
    pyautogui.mouseUp(button='left')
    
def click(button: str="left"):
    pyautogui.mouseDown(button=button)
    time.sleep(1)
    pyautogui.mouseUp(button=button)
    
def press(key: str):
    pyautogui.keyDown(key)
    time.sleep(1)
    pyautogui.keyUp(key)


def tab_in_gta():
    x = gw.getWindowsWithTitle('Grand Theft Auto V')[0]
    
    gta_window.x = x.left
    gta_window.y = x.top
    gta_window.width = x.width
    gta_window.height = x.height
    


    pyautogui.moveTo(gta_window.x + gta_window.width / 2, gta_window.y + gta_window.height / 2)
    pyautogui.click()
    time.sleep(1)
    pyautogui.mouseDown(button='right')
    time.sleep(1)
    pyautogui.mouseUp(button='right')
    time.sleep(1)
    


# %%
## start GTA

if not is_gta_running():
    print("Starting GTA")
    start_gta()
    
    loaded: pyautogui = gta_loaded()
    while not loaded and not DEBUG:
        loaded = gta_loaded()
        time.sleep(1)
    else:
        if not DEBUG:
            print(loaded)
            click_button(loaded)
        loading = story_mode()
        while loading:
            loading = story_mode()
            time.sleep(1)
            
        tab_in_gta()
        
else:
    tab_in_gta()

# %%
## combat
@add_input
def aim():
    pyautogui.mouseDown(button='right')
    
@add_input
def shoot():
    pyautogui.mouseDown(button='left')

@add_input
def stop_shoot():
    pyautogui.mouseUp(button='left')
    
@add_input
def stop_aim():
    pyautogui.mouseUp(button='right')

@add_input
def x_axis(value):
    pyautogui.moveRel(value, 0, duration=0.1)

@add_input
def y_axis(value):
    pyautogui.moveRel(0, value, duration=0.1)
    
@add_input
def cover():
    keyboard.press('q')
    time.sleep(0.1)
    keyboard.release('q')
    
@add_input
def reload():
    keyboard.press('r')
    time.sleep(0.1)
    keyboard.release('r')
    
@add_input
def jump():
    keyboard.press('space')
    time.sleep(0.1)
    keyboard.release('space')
    
@add_input
def sprint():
    keyboard.press('shift')
    
@add_input
def stop_sprint():
    keyboard.release('shift')
    
@add_input
def enter_car():
    keyboard.press('f')
    time.sleep(0.1)
    keyboard.release('f')

    
## movement

@add_input
def forward():
    keyboard.press('w')

@add_input
def stop_forward():
    keyboard.release('w')
    
@add_input
def backward():
    keyboard.press('s')
    
@add_input
def stop_backward():
    keyboard.release('s')
    
@add_input
def left():
    keyboard.press('a')
    
@add_input
def stop_left():
    keyboard.release('a')
    
@add_input
def right():
    keyboard.press('d')
    
@add_input
def stop_right():
    keyboard.release('d')
    

print(len(input_list))

# %%
## CV2 lib
def make_screenshot():
    screenshot = grab_screen((gta_window.x, gta_window.y, gta_window.x + gta_window.width, gta_window.y + gta_window.height))
    return screenshot

    
def process_img(image):
    processed_img = cv2.resize(image, (720,405))
    processed_img = cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB)   
    data = detect_img(processed_img)
    processed_img = np.expand_dims(processed_img, axis=0)
    return processed_img, data

def detect_img(img):
    img_tensor = tf.convert_to_tensor(img, dtype=tf.float32)
    start_time = time.time()
    result = detector(img_tensor)
    end_time = time.time()
    result = {key:value.numpy() for key,value in result.items()}
    
    print("Found %d objects." % len(result["detection_scores"]))
    print("Inference time: ", end_time-start_time)
    
    return result

def draw_boxes(image, boxes, class_names, scores, max_boxes=10, min_score=0.1):
    
    colors = list(ImageColor.colormap.values())
    
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Regular.ttf",
                                25)
    except IOError:
        print("Font not found, using default font.")
        font = ImageFont.load_default()

    for i in range(min(boxes.shape[0], max_boxes)):
        if scores[i] >= min_score:
            ymin, xmin, ymax, xmax = tuple(boxes[i])
            display_str = "{}: {}%".format(class_names[i].decode("ascii"),
                                            int(100 * scores[i]))
            color = colors[hash(class_names[i]) % len(colors)]
            image_pil = Image.fromarray(np.uint8(image)).convert("RGB")
            draw_bounding_box_on_image(
                image_pil,
                ymin,
                xmin,
                ymax,
                xmax,
                color,
                font,
                display_str_list=[display_str])
            np.copyto(image, np.array(image_pil))
    return image


def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               color,
                               font,
                               thickness=4,
                               display_str_list=()):
  """Adds a bounding box to an image."""
  draw = ImageDraw.Draw(image)
  im_width, im_height = image.size
  (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                ymin * im_height, ymax * im_height)
  draw.line([(left, top), (left, bottom), (right, bottom), (right, top),
             (left, top)],
            width=thickness,
            fill=color)


# %%
tab_in_gta()
while (True):
    screenshot = make_screenshot()
    processed_img, data = process_img(screenshot)
    
    image_with_boxes = draw_boxes(
      processed_img, data["detection_boxes"],
      data["detection_class_entities"], data["detection_scores"])
    
    
    cv2.imshow('AI View', image_with_boxes)
    if cv2.waitKey(25) & 0xFF == ord('q') or keyboard.is_pressed('q'):
        cv2.destroyAllWindows()
        break

{
    "name": "AttributeError",
    "message": "module 'tensorflow.security.fuzzing.py.annotation_types' has no attribute 'Float8e4m3fn'",
    "stack": "---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
c:\\Users\\juliu\\Desktop\\AI\\app.ipynb Zelle 1 line 1
     <a href='vscode-notebook-cell:/c%3A/Users/juliu/Desktop/AI/app.ipynb#W0sZmlsZQ%3D%3D?line=14'>15</a> import numpy as np
     <a href='vscode-notebook-cell:/c%3A/Users/juliu/Desktop/AI/app.ipynb#W0sZmlsZQ%3D%3D?line=15'>16</a> import pandas as pd
---> <a href='vscode-notebook-cell:/c%3A/Users/juliu/Desktop/AI/app.ipynb#W0sZmlsZQ%3D%3D?line=17'>18</a> import tensorflow as tf
     <a href='vscode-notebook-cell:/c%3A/Users/juliu/Desktop/AI/app.ipynb#W0sZmlsZQ%3D%3D?line=18'>19</a> print(tf.__version__)
     <a href='vscode-notebook-cell:/c%3A/Users/juliu/Desktop/AI/app.ipynb#W0sZmlsZQ%3D%3D?line=19'>20</a> import tensorflow_hub as hub

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\__init__.py:39
     36 import sys as _sys
     37 import typing as _typing
---> 39 from tensorflow.python.tools import module_util as _module_util
     40 from tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader
     41 from tensorflow.python.util.lazy_loader import KerasLazyLoader as _KerasLazyLoader

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\__init__.py:42
     36 from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
     38 # pylint: enable=wildcard-import
     39 
     40 # from tensorflow.python import keras
     41 # from tensorflow.python.layers import layers
---> 42 from tensorflow.python.saved_model import saved_model
     43 from tensorflow.python.tpu import api
     45 # Sub-package for performing i/o directly instead of via ops in a graph.

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\saved_model\\saved_model.py:31
     29 from tensorflow.python.saved_model.fingerprinting import Fingerprint
     30 from tensorflow.python.saved_model.fingerprinting import read_fingerprint
---> 31 from tensorflow.python.saved_model.load import load
     32 from tensorflow.python.saved_model.save import save
     33 # pylint: enable=unused-import
     34 # pylint: disable=wildcard-import

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\saved_model\\load.py:31
     29 from tensorflow.python.checkpoint import restore
     30 from tensorflow.python.distribute import distribute_lib
---> 31 from tensorflow.python.distribute import distribute_utils
     32 from tensorflow.python.distribute import values_util
     33 from tensorflow.python.eager import context

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\distribute\\distribute_utils.py:22
     19 import threading
     21 from tensorflow.python.distribute import distribute_lib
---> 22 from tensorflow.python.distribute import tpu_values as tpu_values_lib
     23 from tensorflow.python.distribute import values as values_lib
     24 from tensorflow.python.distribute.reduce_util import ReduceOp

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\distribute\\tpu_values.py:22
     15 \"\"\"Various classes representing TPU distributed values.
     16 
     17 Note that the tests are in values_test.py .
     18 
     19 \"\"\"
     21 from tensorflow.python.distribute import packed_distributed_variable as packed
---> 22 from tensorflow.python.distribute import tpu_replicated_variable
     23 from tensorflow.python.distribute import tpu_util
     24 from tensorflow.python.distribute import values

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\distribute\\tpu_replicated_variable.py:23
     20 from collections import abc
     21 import contextlib
---> 23 from tensorflow.python.compiler.xla.experimental import xla_sharding
     24 from tensorflow.python.distribute import tpu_util
     25 from tensorflow.python.eager import context

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\compiler\\xla\\__init__.py:19
     17 # pylint: disable=unused-import
     18 from tensorflow.python.compiler.xla import jit
---> 19 from tensorflow.python.compiler.xla import xla
     20 # pylint: enable=unused-import

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\python\\compiler\\xla\\xla.py:20
     15 \"\"\"xla is an experimental library that provides XLA support APIs.\"\"\"
     17 import contextlib
---> 20 from tensorflow.compiler.jit.ops import xla_ops
     21 from tensorflow.compiler.jit.ops import xla_ops_grad  # pylint: disable=unused-import
     22 from tensorflow.core.framework import attr_value_pb2

File c:\\Users\\juliu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\tensorflow\\compiler\\jit\\ops\\xla_ops.py:25
     22 from typing import TypeVar, List, Any
     23 from typing_extensions import Annotated
---> 25 TV_XlaClusterOutput_T = TypeVar(\"TV_XlaClusterOutput_T\", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant)
     27 @_dispatch.add_fallback_dispatch_list
     28 @_dispatch.add_type_based_api_dispatcher
     29 @tf_export('xla_cluster_output')
     30 def xla_cluster_output(input: Annotated[Any, TV_XlaClusterOutput_T], name=None) -> Annotated[Any, TV_XlaClusterOutput_T]:
     31   r\"\"\"Operator that connects the output of an XLA computation to other consumer graph nodes.
     32 
     33   Args:
   (...)
     38     A `Tensor`. Has the same type as `input`.
     39   \"\"\"

AttributeError: module 'tensorflow.security.fuzzing.py.annotation_types' has no attribute 'Float8e4m3fn'"
}

我重新安装了 Tensorflow,希望错误能够消失。

python tensorflow attributeerror
1个回答
0
投票

运行“pip install --upgrade tensorflow”为我解决了这个问题。

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