python-3.x Keras版本错误

x33g5p2x  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(143)

我正在Udacity的自动驾驶汽车项目,教汽车自动运行(行为克隆)。
我得到一个奇怪的Unicode错误。
所述错误如下:
(dl)Vidits-MacBook-Pro-2:BehavioralClonning-master ViditShah $python www.example.com model.h5使用TensorFlow后端。您使用的是Keras版本b'2.1.2 ',但模型是使用b'1.2.1'回溯构建的(最近的调用最后进行):drive.py(模型配置,自定义对象=自定义对象)文件"/用户/ViditShah/anaconda/环境/dl/库/Python 3.6/站点包/keras/模型. py ",第314行,在model_from_config中返回layer_module.反序列化器drive.py在deserialize_keras_object列表中models.py(配置文件,自定义对象=自定义对象)文件"/用户/ViditShah/anaconda/环境/dl/库/python3.6/站点包/keras/层/init. py ",第55行,在反序列化可打印模块名称="层"中)文件"/用户/可视化沙阿/anaconda/envs/dl/库/python3.6/站点包/keras/实用程序/通用实用程序. py ",第140行,在反序列化keras对象列表(自定义对象.项())中))文件"/用户/可视化沙阿/anaconda/envs/dl/库/python3.6/站点包/keras/层/www.example.com",第699行,在from_config函数中= func_load(配置['函数'],全局变量=全局变量)文件"/用户/ViditShah/anaconda/envs/dl/lib/python3.6/站点包/keras/utils/generic_utils. py ",第224行,在func_load中原始代码= codecs. decode(代码.编码('ascii'),'base64')Unicode编码错误:"ascii"编解码器无法对位置0中的字符"\xe3"进行编码:序数不在范围内(128)(custom_objects.items()))) File "/Users/ViditShah/anaconda/envs/dl/lib/python3.6/site-packages/keras/models.py", line 1323, in from_config layer = layer_module.deserialize(conf, custom_objects=custom_objects) File "/Users/ViditShah/anaconda/envs/dl/lib/python3.6/site-packages/keras/layers/init.py", line 55, in deserialize printable_module_name='layer') File "/Users/ViditShah/anaconda/envs/dl/lib/python3.6/site-packages/keras/utils/generic_utils.py", line 140, in deserialize_keras_object list(custom_objects.items()))) File "/Users/ViditShah/anaconda/envs/dl/lib/python3.6/site-packages/keras/layers/core.py", line 699, in from_config function = func_load(config['function'], globs=globs) File "/Users/ViditShah/anaconda/envs/dl/lib/python3.6/site-packages/keras/utils/generic_utils.py", line 224, in func_load raw_code = codecs.decode(code.encode('ascii'), 'base64') UnicodeEncodeError: 'ascii' codec can't encode character '\xe3' in position 0: ordinal not in range(128)
我在我的水蟒环境DL。
文件www.example.com如下所示。(此文件是在分配任务期间提供的,未建议进行编辑)。drive.py is as follows.(This file was given during assignment and no edits has been suggested).

import argparse
import base64
from datetime import datetime
import os
import shutil

import numpy as np
import socketio
import eventlet
import eventlet.wsgi
from PIL import Image
from flask import Flask
from io import BytesIO

from keras.models import load_model
import h5py
from keras import __version__ as keras_version

sio = socketio.Server()
app = Flask(__name__)
model = None
prev_image_array = None


class SimplePIController:
    def __init__(self, Kp, Ki):
        self.Kp = Kp
        self.Ki = Ki
        self.set_point = 0.
        self.error = 0.
        self.integral = 0.

    def set_desired(self, desired):
        self.set_point = desired

    def update(self, measurement):
        # proportional error
        self.error = self.set_point - measurement

        # integral error
        self.integral += self.error

        return self.Kp * self.error + self.Ki * self.integral


controller = SimplePIController(0.1, 0.002)
set_speed = 9
controller.set_desired(set_speed)


@sio.on('telemetry')
def telemetry(sid, data):
    if data:
        # The current steering angle of the car
        steering_angle = data["steering_angle"]
        # The current throttle of the car
        throttle = data["throttle"]
        # The current speed of the car
        speed = data["speed"]
        # The current image from the center camera of the car
        imgString = data["image"]
        image = Image.open(BytesIO(base64.b64decode(imgString)))
        image_array = np.asarray(image)
        steering_angle = float(model.predict(image_array[None, :, :, :], batch_size=1))

        throttle = controller.update(float(speed))

        print(steering_angle, throttle)
        send_control(steering_angle, throttle)

        # save frame
        if args.image_folder != '':
            timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3]
            image_filename = os.path.join(args.image_folder, timestamp)
            image.save('{}.jpg'.format(image_filename))
    else:
        # NOTE: DON'T EDIT THIS.
        sio.emit('manual', data={}, skip_sid=True)


@sio.on('connect')
def connect(sid, environ):
    print("connect ", sid)
    send_control(0, 0)


def send_control(steering_angle, throttle):
    sio.emit(
        "steer",
        data={
            'steering_angle': steering_angle.__str__(),
            'throttle': throttle.__str__()
        },
        skip_sid=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Remote Driving')
    parser.add_argument(
        'model',
        type=str,
        help='Path to model h5 file. Model should be on the same path.'
    )
    parser.add_argument(
        'image_folder',
        type=str,
        nargs='?',
        default='',
        help='Path to image folder. This is where the images from the run will be saved.'
    )
    args = parser.parse_args()

    # check that model Keras version is same as local Keras version
    f = h5py.File(args.model, mode='r')
    model_version = f.attrs.get('keras_version')
    keras_version = str(keras_version).encode('utf8')

    if model_version != keras_version:
        print('You are using Keras version ', keras_version,
              ', but the model was built using ', model_version)

    model = load_model(args.model)

    if args.image_folder != '':
        print("Creating image folder at {}".format(args.image_folder))
        if not os.path.exists(args.image_folder):
            os.makedirs(args.image_folder)
        else:
            shutil.rmtree(args.image_folder)
            os.makedirs(args.image_folder)
        print("RECORDING THIS RUN ...")
    else:
        print("NOT RECORDING THIS RUN ...")

    # wrap Flask application with engineio's middleware
    app = socketio.Middleware(sio, app)

    # deploy as an eventlet WSGI server
    eventlet.wsgi.server(eventlet.listen(('', 4567)), app)
332nm8kg

332nm8kg1#

您收到此错误是因为您尝试加载的模型似乎是在Keras的早期版本中训练和保存的,而不是您正在使用的版本,如以下建议:
您正在使用Keras版本b'2.1.2',但模型是使用b'1.2.1' Traceback构建的(最近的调用最后进行):文件“drive.py“,第122行,在模型=负载模型(参数模型)中
看起来这个问题的解决方案可能是用你计划使用的相同版本训练你的模型,这样你就可以顺利地加载它。另一个选择是**使用1.2.1版本加载模型并使用它。
这可能是由于Keras在不同版本之间保存模型的方式不同,因为在v.1.2.1和v.2.1.2之间应该发生了一些主要的变化。

相关问题