Rust Call Tensorflow

This example shows how to call python tensorflow with rust language.

This example is based on star_for_rust, which enables rust calls other scripts. Here, we call tensorflow python code with rust language. The code is simple.

Background

Install

Step by Step

1. Python code to be called

   
import tensorflow as tf
a = tf.constant(5,name="input_a")
b = tf.constant(3,name="input_b")
c = tf.multiply(a,b,name="input_c")
d = tf.add(a,b,name="input_d")
e = tf.add(c,d,name="input_c_d")
sess = tf.Session()
r = sess.run(e)
print(r)     
  

2. Rust code

  • Cargo.toml
[package]
name = "rustcalltensorflow"
version = "0.1.0"
authors = ["srplab"]

[dependencies]
starcore_for_rust = {git="https://github.com/srplab/starcore_for_rust"}
  
  • Initialize CLE
let Service = starrust::InitSimple(&"test",&"123", 0, 0,&[]);
starrust::RegMsgCallBack_P(MsgCallBack);
let SrvGroup = Service.Get(&"_ServiceGroup").ToSrvGroup();
Service.CheckPassword(false);
  
  • Initialize python
let initResult = SrvGroup.InitRaw(&"python", &Service);
let python = Service.ImportRawContext(&"python", &"", false, &"");
  
  • Call tensorflow
star_call!(python,"import","tensorflow");
let tf = python.GetObject(&"tensorflow");    

let a = star_callobject!(tf,"constant",5,star_dict!(SrvGroup,"name"=>"input_a")); 
let b = star_callobject!(tf,"constant",3,star_dict!(SrvGroup,"name"=>"input_b"));

let c = star_callobject!(tf,"multiply",a, b,star_dict!(SrvGroup,"name"=>"mul_c"));  
let d = star_callobject!(tf,"add", a, b,star_dict!(SrvGroup,"name"=>"add_d"));

let e = star_callobject!(tf,"add",c, d, star_dict!(SrvGroup,"name"=>"add_e_d"));

let sess = star_callobject!(tf,"Session",);
let r = star_callobject!(sess,"run", e);

println!("{}",r.ToString());
  

Sample Download

rustcalltensorflow.zip