2017-09-14 103 views
0

我試圖用Mxnet-js library在瀏覽器中顯示我的Mxnet訓練過的模型。我正在關注Mxnet-js git自述文件。Mxnet -js-將字節寫入字符串

他們提供了一個python腳本。 ./tool/model2json,將模型轉換爲json文件。 當我運行此腳本與我的模型,我得到錯誤:

TypeError: write() argument must be str, not bytes 

得到這個錯誤很有道理,因爲,我怎麼能寫字節到在字符串模式打開的文件。在線路

模型= base64.b64encode(字節(開放(sys.argv中[3], 'RB')。讀()))

他們正在閱讀它以字節爲單位,但在線路

張開(sys.argv中1, 'W'),爲FO:

它們以串模式和線

fo.write(模型)打開文件

它們將字節寫入字符串。

我在這裏錯過了什麼嗎?他們爲什麼要寫字節字符串

#!/usr/bin/env python 
"""Simple util to convert mxnet model to json format.""" 
import sys 
import json 
import base64 

if len(sys.argv) < 4: 
    print('Usage: <output.json> <symbol.json> <model.param> 
           [mean_image.nd] [synset]') 
    exit(0) 

symbol_json = open(sys.argv[2]).read() 
model = base64.b64encode(bytes(open(sys.argv[3], 'rb').read())) 
mean_image = None 
synset = None 

if len(sys.argv) > 4: 
    mean_image = base64.b64encode(bytes(open(sys.argv[4], 
             'rb').read())) 

if len(sys.argv) > 5: 
    synset = [l.strip() for l in open(sys.argv[5]).readlines()] 

with open(sys.argv[1], 'w') as fo: 

    fo.write('{\n\"symbol\":\n') 
    fo.write(symbol_json) 
    if synset: 
     fo.write(',\n\"synset\": ') 
     fo.write(json.dumps(synset)) 
    fo.write(',\n\"parambase64\": \"') 

    fo.write(model) 
    fo.write('\"\n') 
    if mean_image is not None: 
     fo.write(',\n\"meanimgbase64\": \"') 
     fo.write(mean_image) 
     fo.write('\"\n') 
fo.write('}\n') 

回答

1

TL; DR 您使用的是Python3嗎?如果是這樣 - 請使用Python2,並且應該可以工作!

更多詳細信息: 代碼打開模型的二進制加權文件,讀取二進制數據,構造一個Bytes序列(Python builtin類型),並將其轉換爲String。

現在,雖然Python 2隱式地將字節轉換爲字符串,但Python 3並沒有這樣做。所以我懷疑你正在使用Python 3,然後你的轉換是不正確的。

要檢查您的版本上運行python --version 如果你確實使用Python 3,你可以嘗試更新行model2json.py 12有明確的轉換: model = str(base64.b64encode(bytes(open(sys.argv[3], 'rb').read()))) 注意使用Python 3,你還需要啓動本地網絡服務器使用不同於readme.md上記錄的命令的命令:$ python3 -m http.server

我的建議是你使用Python 2,因爲這個整個repo是爲它編寫的,並且使用Python3可能會遇到其他問題。