def build_model(n_nodes, size, opv=15): OnnxAdd, OnnxIdentity = loadop('Add', 'Identity') x = 'X' for n in range(n_nodes): y = OnnxAdd(x, numpy.random.randn(size).astype(numpy.float32), op_version=opv) x = y final = OnnxIdentity(x, op_version=opv, output_names=['Y']) x = numpy.zeros((10, 10), dtype=numpy.float32) return final.to_onnx({'X': x}, {'Y': x}, target_opset=opv)
def test_onnx_abs(self): OnnxAbs = loadop("Abs") ov = OnnxAbs('X', output_names=['Y']) onx = ov.to_onnx(numpy.float32, numpy.float32, verbose=0) sub = OnnxSubOnnx(onx, 'X', output_names=['Y']) onx = sub.to_onnx(numpy.float32, numpy.float32, verbose=0) oinf = OnnxInference(onx) x = numpy.array([-2, 2], dtype=numpy.float32) got = oinf.run({'X': x}) self.assertEqualArray(numpy.abs(x), got['Y'])
def test_onnx_cast(self): OnnxCast = loadop("Cast") ov = OnnxCast('X', to=numpy.int64, output_names=['Y']) onx = ov.to_onnx(numpy.float32, numpy.float32, verbose=0) sub = OnnxSubOnnx(onx, 'X', output_names=['Y']) onx = sub.to_onnx(numpy.float32, numpy.int64, verbose=0) r = repr(sub) self.assertStartsWith('OnnxSubOnnx(..., output_name', r) oinf = OnnxInference(onx) x = numpy.array([-2.4, 2.4], dtype=numpy.float32) got = oinf.run({'X': x}) self.assertEqualArray(x.astype(numpy.int64), got['Y'])
def test_onnx_shape_inference(self): OnnxAdd = loadop('Add') dtype = numpy.float32 for opset in TestOnnxShapeInferenceXop.opsets: with self.subTest(opset=opset): cop = OnnxAdd('X', numpy.array([[1]], dtype=dtype), op_version=opset) cop4 = OnnxAdd(cop, numpy.array([[2]], dtype=dtype), output_names=['Y']) vari = Variable('X', numpy.float32, [None, None]) model_def = cop4.to_onnx([vari], run_shape=False) rt = OnnxShapeInference(model_def) out = rt.run() self.assertIn('X', out) self.assertIn('Y', out) y = out['Y'] self.assertEqual(numpy.float32, y.dtype) self.assertEqual(['_0', '_1'], y.shape)
def test_onnx_lr(self): X, y = make_regression(n_features=2) # pylint: disable=W0632 lr = LinearRegression() lr.fit(X, y) X32 = X.astype(numpy.float32) OnnxIdentity, OnnxReshape = loadop("Identity", "Reshape") ov = OnnxIdentity('X') self.assertRaise(lambda: OnnxSubEstimator(lr, ov), NotImplementedError) sub = OnnxSubEstimator(lr, ov, op_version=max_supported_opset(), initial_types=X32[:1]) r = repr(sub) self.assertStartsWith('OnnxSubEstimator(LinearRegression()', r) last = OnnxReshape(sub, numpy.array([-1], dtype=numpy.int64), output_names=['Y']) onx = last.to_onnx(numpy.float32, numpy.float32, verbose=0) oinf = OnnxInference(onx) got = oinf.run({'X': X32}) expected = lr.predict(X32) self.assertEqualArray(expected, got['Y'], decimal=4)