Theano Shared Variable



import numpy as np import theano.tensor as T import theano # Define a shared variable, np assigned an initial value 0, the fixed type, and the latter are unified state, state=theano.shared(np.array(0,dtype=np.float64),'state') # Accumulated value increase=T.scalar('increase',dtype=state.dtype)# Note that this must be set the same as dtype the state, rather than np.float64 # Accumulator, called the input parameters to Increase updates, an output state, the accumulation process, is now put into state state + inc accumulator=theano.function([increase],state,updates=[(state,state+increase)]) # In this case, the first is the initial value of 0, only when the next output will appear 10. #print(accumulator(10)) #0 #print(accumulator(10)) #10 #get_value can be used to extract the parameter value. print(state.get_value()) accumulator(1) print(state.get_value()) #0 accumulator(10) print(state.get_value()) #1 It can be used to re-set the parameters #set_value state.set_value(-1) accumulator(3) print(state.get_value()) #2 # Only temporary use Shared variables, it does not need to update: # You can define a temporary substitute to a state, we also need to define a time dtype temp_func=state*2+increase a=T.scalar(dtype=state.dtype) # Input value is [increase, a], substituting equivalent to a state, # Output is tmp_func, givens is trying to replace what what skip_shared=theano.function([increase,a],temp_func,givens=[(state,a)]) Was originally entered # inc = 1, a = 3, skip_shared givens in such state = 3 print(skip_shared(2,3)) #8 3*2 + 2 = 8 print (state.get_value()) #2


0.0 1.0 11.0 2.0 8.0 2.0