如何将2D列表转换为json

时间:2017-02-11 21:25:15

标签: python

我有在keras训练的MLP重量。权重是2D数组的列表。如何在json文件中保存权重?我的目标是将存储的权重发送到另一台服务器。如果你能找到任何东西,请告诉我。我到处寻找,但无法找到解决方案。这是我的代码:

# Create first network with Keras
from keras.models import Sequential
from keras.layers import Dense
from bottle import route, run
import socket
import numpy 
import h5py
import cPickle
import httplib
import urllib2
import urllib
import codecs
import simplejson as json 

def main():
    seed = 7
    numpy.random.seed(seed)
    # load pima indians dataset
    dataset = numpy.loadtxt('pima-indians-diabetes.data', delimiter=",")
    # split into input (X) and output (Y) variables
    X = dataset[:,0:8]
    Y = dataset[:,8]
    # create model
    model = Sequential()
    model.add(Dense(20, input_dim=8, init='uniform', activation='relu'))
    model.add(Dense(9, init='uniform', activation='relu'))
    model.add(Dense(1, init='uniform', activation='sigmoid'))
    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    # Fit the model
    model.fit(X, Y, nb_epoch=150, batch_size=20, verbose = False)
    # evaluate the model
    scores = model.evaluate(X, Y)
    # print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
    weights = model.get_weights()
    with open('data.txt', 'w') as outfile:
         json.dump(weights, outfile)
main()

我得到的错误是:

Using TensorFlow backend.
 32/768 [>.............................] - ETA: 0sTraceback (most recent call last):
  File "test.py", line 38, in <module>
    main()
  File "test.py", line 37, in main
    json.dump(weights, outfile)
  File "/usr/local/lib/python2.7/dist-packages/simplejson/__init__.py", line 276, in dump
    for chunk in iterable:
  File "/usr/local/lib/python2.7/dist-packages/simplejson/encoder.py", line 665, in _iterencode
    for chunk in _iterencode_list(o, _current_indent_level):
  File "/usr/local/lib/python2.7/dist-packages/simplejson/encoder.py", line 515, in _iterencode_list
    for chunk in chunks:
  File "/usr/local/lib/python2.7/dist-packages/simplejson/encoder.py", line 697, in _iterencode
    o = _default(o)
  File "/usr/local/lib/python2.7/dist-packages/simplejson/encoder.py", line 268, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: array([[ 0.11374838, -0.02957115, -0.23768419,  0.25968653, -0.09367259,
        ... , -0.062304  , -0.05544948]], dtype=float32) is not JSON serializable

0 个答案:

没有答案