Skip to content

Instantly share code, notes, and snippets.

@arafatkatze
Last active July 16, 2019 17:10
Show Gist options
  • Save arafatkatze/7cec701536f33d3bf8899b123b143eb1 to your computer and use it in GitHub Desktop.
Save arafatkatze/7cec701536f33d3bf8899b123b143eb1 to your computer and use it in GitHub Desktop.
require 'tensorflow'
graph = Tensorflow::Graph.new
tensor_1 = Tensorflow::Tensor.new([[2, 2.3], [ 10, 6.2]])
tensor_2 = Tensorflow::Tensor.new([[4, 3.2], [ 47, 1.2]])
placeholder_1 = graph.placeholder('tensor1', tensor_1.type_num)
placeholder_2 = graph.placeholder('tensor2', tensor_2.type_num)
opspec = Tensorflow::OpSpec.new('Addition_of_tensors', 'Add', nil, [placeholder_1, placeholder_2])
op = graph.AddOperation(opspec)
session_op = Tensorflow::Session_options.new
session = Tensorflow::Session.new(graph, session_op)
hash = {}
hash[placeholder_1] = tensor_1
hash[placeholder_2] = tensor_2
result = session.run(hash, [op.output(0)], [])
print result[0], "\n"
@zverok
Copy link

zverok commented Jul 7, 2016

Just a set of small "more ruby-ish" code changes for this example:

graph = Graph.new
input1 = graph.placeholder(:input1, Tensorflow::TF_DOUBLE, [2,3])
input2 = graph.placeholder(:input2, Tensorflow::TF_DOUBLE, [2,3])
graph.op_definer(:Add,:output, [input1, input2], "", nil) # or maybe even :add, I'm not sure if it is internal TensorFlow op
encoder = Tensorflow::GraphDef.encode(graph.graph_def)
session = Session.new
graph.graph_def_raw = encoder
session.extend_graph(graph)
input1 = Tensor.new([[1.0,3.0, 5.0],[2.0,4.0, 7.0]])
input2 = Tensor.new([[-5.0,1.2,4.5],[8.0,2.3, 3.1]])
input = {
  input1: input1.tensor,
  input2: input2.tensor
}
result = session.run(input, [:output], nil)
puts result.first

Also, note that sometimes you use namespace (Tensorflow::GraphDef), and sometimes not (Session.new). Also, I suppose TensorFlow is more correct as a namespace name.

(It is pretty small "first glance" changes, just for the showcase sake)

@chrhansen
Copy link

Yeah, definitely not the empty () parenthesis if not parameters.

Regarding using symbols instead of strings, we need to be careful initially, because TensorFlow complains if we pass it a Symbol as the key. So at some point we should convert any placeholder names/keys to String before passing them on to TensorFlow and maybe use HashWithIndifferentAccess when a tensor is fetched from TensorFlow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment