Reputation: 662
I have basic model in python tensorflow I want to save it to onnx file how can I do this. I have tried using onnx.save
function I am getting error.
File "tenserflowbase.py", line 21, in <module> onnx.save(trained_model,'model.onxx')
File "C:\Users\Parag_IK\Anaconda3\lib\site-packages\onnx\__init__.py", line 184, in save_model proto = write_external_data_tensors(proto, basepath)
File "C:\Users\Parag_IK\Anaconda3\lib\site packages\onnx\external_data_helper.py", line 225, in write_external_data_tensors
for tensor in _get_all_tensors(model):
File "C:\Users\Parag_IK\Anaconda3\lib\site packages\onnx\external_data_helper.py", line 170, in _get_initializer_tensors
for initializer in onnx_model_proto.graph.initializer:
AttributeError: 'History' object has no attribute 'graph'**
My code is below:
import onnx
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
tf.logging.set_verbosity(tf.logging.ERROR)
mar_budget = np.array([60, 80, 100 , 30, 50, 20, 90, 10], dtype=float)
subs_gained = np.array([160, 200, 240, 100, 140, 80, 220, 60], dtype=float)
for i, c in enumerate(mar_budget):
print("{} Market budget = {} new subscribers gained".format(c, subs_gained[i]))
X_train, X_test, y_train, y_test = train_test_split(mar_budget, subs_gained,
random_state=42, train_size=0.8, test_size=0.2)
layer_0 = tf.keras.layers.Dense(units=1, input_shape=[1])
model = tf.keras.Sequential([layer_0])
model = tf.keras.Sequential([layer_0])
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))
trained_model = model.fit(X_train, y_train, epochs=1000, verbose=False)
onnx.save(trained_model,'model.onxx')
print("Finished training the model")
print(model.predict([80.0]))
Upvotes: 0
Views: 2977
Reputation: 1749
I think if I am not wrong, in order to use onnx.save()
, the model should create the graph in onnx
functions.
So I would suggest using the tf2onnx
library, which has a function convert the tf session graph into onnx graph.
onnx_graph = tf2onnx.tfonnx.process_tf_graph(sess.graph, ...)
For example a full code would be:
import tensorflow as tf
import tf2onnx
with tf.Session() as sess:
x = tf.placeholder(tf.float32, [2, 3], name="input")
x_ = tf.add(x, x)
_ = tf.identity(x_, name="output")
onnx_graph = tf2onnx.tfonnx.process_tf_graph(sess.graph, input_names=["input:0"], output_names=["output:0"])
model_proto = onnx_graph.make_model("test")
with open("/tmp/model.onnx", "wb") as f:
f.write(model_proto.SerializeToString())
Hope this helps.
Reference: tensorflow-onnx
Upvotes: 1