HOST = tc.host.Host("http://127.0.0.1:8702")
ENDPOINT = "/transact/hypothetical"
# define the shape of the layer
# initialize a new execution context
# define the sigmoid activation function
# learn more at https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6
def sigmoid(x: tc.tensor.Tensor) -> tc.tensor.Tensor:
return 1 / (1 + (-x).exp())
# define the weights and bias of the layer itself
weights = np.random.random([input_size, output_size])
cxt.weights = tc.tensor.Dense.load(weights.shape, tc.F32, weights.flatten().tolist())
bias = np.random.random([output_size])
cxt.bias = tc.tensor.Dense.load(bias.shape, tc.F32, bias.flatten().tolist())
# define evaluating the layer with respect to a given input
# the @tc.closure annotation tells TinyChain to capture the given states
@tc.closure(cxt.bias, cxt.weights, cxt.sigmoid)
def evaluate(input: tc.tensor.Tensor) -> tc.tensor.Tensor:
activation = tc.tensor.einsum("ij,jk->ik", [cxt.weights, input]) + cxt.bias
return cxt.sigmoid(x=activation) # remember: a POST op requires named arguments!
if __name__ == "__main__":
# check that our implementation works as expected
cxt.inputs = tc.tensor.Dense.load([1, input_size], tc.F32, [1, 2])
cxt.result = cxt.evaluate(input=cxt.inputs)
print(HOST.post(ENDPOINT, cxt))