json文件可能有误

时间:2017-04-15 11:46:26

标签: python python-3.x keras

现在我正在使用keras。 我正在制作图像识别系统。 但是我收到了一个错误,

Using TensorFlow backend.
Traceback (most recent call last):
  File "use_model.py", line 35, in <module>
    model = model_from_json(open(keras_model).read())
  File "/Users/xx/anaconda/envs/py36/lib/python3.6/site-packages/keras/models.py", line 212, in model_from_json
    config = json.loads(json_string)
  File "/Users/xx/anaconda/envs/py36/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Users/xx/anaconda/envs/py36/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/xx/anaconda/envs/py36/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我认为json文件对我的应用程序不好,所以我删除了test.json。 但在那个时候,我收到了一个错误

Using TensorFlow backend.
Traceback (most recent call last):
  File "use_model.py", line 35, in <module>
    model = model_from_json(open(keras_model).read())
FileNotFoundError: [Errno 2] No such file or directory: './test.json'

我认为这很自然(因为我删除了json文件) 我不知道该怎么解决。我该怎么办? 我的整个代码就像

# coding:utf-8
import keras
import sys, os
import scipy
import scipy.misc
import numpy as np
from keras.models import model_from_json

import json

imsize = (32, 32)
testpic = "./testpic/"
keras_model = "./test.json"
keras_param = "./test.hdf5"


def load_image(path):
    img = scipy.misc.imread(path, mode="RGB")
    img = scipy.misc.imresize(img, imsize)
    img = img / 255.0
    return img

def get_file(dir_path):
    """
    ['244573113_thumb.jpg', 'car1.jpg', 'car2.jpg', 'car3.jpg', 'cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'dog1.jpg', 'dog2.jpg', 'dog3.jpg', 'dog4.jpg', 'dog5.jpg', 'dog6.jpg', 'dog7.jpg']
    """
    filenames = os.listdir(dir_path)
    return filenames

if __name__ == "__main__":

    pic = get_file(testpic)

    model = model_from_json(open(keras_model).read())
    model.load_weights(keras_param)
    model.summary()

    for i in pic:
        print(i) 
        img = load_image(testpic + i)
        #vec = model.predict(np.array([img]), batch_size=1)
        prd = model.predict(np.array([img]))
        print(prd)
        prelabel = np.argmax(prd, axis=1)


        if prelabel == 0:
            print(">>>cat")
        elif prelabel == 1:
            print(">>> dog")
        elif prelabel == 2:
            print(">>> other")

        print("#"*55)

1 个答案:

答案 0 :(得分:0)

删除之前json文件中有什么内容?

看起来它是一个无效的json文件。也许它是空的?

>>> import json
>>> json.loads('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

或许文件根本不包含json文档:

>>> json.loads('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是一个示例,让您了解json文件中的预期内容:

import json
from keras.models import Model
from keras.layers import Input, Dense

a = Input(shape=(32,))
b = Dense(32)(a)
model = Model(inputs=a, outputs=b)

print(model.to_json(indent=4))

<强>输出

{
    "config": {
        "input_layers": [
            [
                "input_2",
                0,
                0
            ]
        ],
        "output_layers": [
            [
                "dense_2",
                0,
                0
            ]
        ],
        "name": "model_3",
        "layers": [
            {
                "config": {
                    "batch_input_shape": [
                        null,
                        32
                    ],
                    "name": "input_2",
                    "sparse": false,
                    "dtype": "float32"
                },
                "name": "input_2",
                "inbound_nodes": [],
                "class_name": "InputLayer"
            },
            {
                "config": {
                    "bias_initializer": {
                        "config": {},
                        "class_name": "Zeros"
                    },
                    "bias_regularizer": null,
                    "name": "dense_2",
                    "kernel_regularizer": null,
                    "activity_regularizer": null,
                    "activation": "linear",
                    "units": 32,
                    "use_bias": true,
                    "bias_constraint": null,
                    "kernel_initializer": {
                        "config": {
                            "distribution": "uniform",
                            "seed": null,
                            "mode": "fan_avg",
                            "scale": 1.0
                        },
                        "class_name": "VarianceScaling"
                    },
                    "trainable": true,
                    "kernel_constraint": null
                },
                "name": "dense_2",
                "inbound_nodes": [
                    [
                        [
                            "input_2",
                            0,
                            0,
                            {}
                        ]
                    ]
                ],
                "class_name": "Dense"
            }
        ]
    },
    "keras_version": "2.0.3",
    "class_name": "Model",
    "backend": "tensorflow"
}