importsysimportosimporttorchimporttorch.nnasnnimporttorch.nn.functionalasFimportonnxfromcollectionsimportOrderedDictimporttensorflowastffromtorch.autogradimportVariablefromonnx_tf.backendimportprepare# Load the trained model from filetrained_dict=torch.load(sys.argv[1],map_location={'cuda:0':'cpu'})trained_model=MLP(784,[256,256],10)trained_model.load_state_dict(trained_dict)ifnotos.path.exists("%s"%sys.argv[2]):os.makedirs("%s"%sys.argv[2])# Export the trained model to ONNXdummy_input=Variable(torch.randn(1,1,28,28))# one black and white 28 x 28 picture will be the input to the modeltorch.onnx.export(trained_model,dummy_input,"%s/mnist.onnx"%sys.argv[2])# Load the ONNX filemodel=onnx.load("%s/mnist.onnx"%sys.argv[2])# Import the ONNX model to Tensorflowtf_rep=prepare(model)tf_rep.export_graph("%s/mnist.pb"%sys.argv[2])converter=tf.lite.TFLiteConverter.from_frozen_graph("%s/mnist.pb"%sys.argv[2],tf_rep.inputs,tf_rep.outputs)tflite_model=converter.convert()withopen("%s/mnist.tflite"%sys.argv[2],"wb")asf:f.write(tflite_model)