| 804 | return inputs, initial_state, constants |
| 805 | |
| 806 | def reset_states(self, states=None): |
| 807 | if not self.stateful: |
| 808 | raise AttributeError('Layer must be stateful.') |
| 809 | spec_shape = None if self.input_spec is None else self.input_spec[0].shape |
| 810 | if spec_shape is None: |
| 811 | # It is possible to have spec shape to be None, eg when construct a RNN |
| 812 | # with a custom cell, or standard RNN layers (LSTM/GRU) which we only know |
| 813 | # it has 3 dim input, but not its full shape spec before build(). |
| 814 | batch_size = None |
| 815 | else: |
| 816 | batch_size = spec_shape[1] if self.time_major else spec_shape[0] |
| 817 | if not batch_size: |
| 818 | raise ValueError('If a RNN is stateful, it needs to know ' |
| 819 | 'its batch size. Specify the batch size ' |
| 820 | 'of your input tensors: \n' |
| 821 | '- If using a Sequential model, ' |
| 822 | 'specify the batch size by passing ' |
| 823 | 'a `batch_input_shape` ' |
| 824 | 'argument to your first layer.\n' |
| 825 | '- If using the functional API, specify ' |
| 826 | 'the batch size by passing a ' |
| 827 | '`batch_shape` argument to your Input layer.') |
| 828 | # initialize state if None |
| 829 | if nest.flatten(self.states)[0] is None: |
| 830 | def create_state_variable(state): |
| 831 | return K.zeros([batch_size] + tensor_shape.as_shape(state).as_list()) |
| 832 | self.states = nest.map_structure( |
| 833 | create_state_variable, self.cell.state_size) |
| 834 | if not nest.is_sequence(self.states): |
| 835 | self.states = [self.states] |
| 836 | elif states is None: |
| 837 | for state, size in zip(nest.flatten(self.states), |
| 838 | nest.flatten(self.cell.state_size)): |
| 839 | K.set_value(state, np.zeros([batch_size] + |
| 840 | tensor_shape.as_shape(size).as_list())) |
| 841 | else: |
| 842 | flat_states = nest.flatten(self.states) |
| 843 | flat_input_states = nest.flatten(states) |
| 844 | if len(flat_input_states) != len(flat_states): |
| 845 | raise ValueError('Layer ' + self.name + ' expects ' + |
| 846 | str(len(flat_states)) + ' states, ' |
| 847 | 'but it received ' + str(len(flat_input_states)) + |
| 848 | ' state values. Input received: ' + str(states)) |
| 849 | set_value_tuples = [] |
| 850 | for i, (value, state) in enumerate(zip(flat_input_states, |
| 851 | flat_states)): |
| 852 | if value.shape != state.shape: |
| 853 | raise ValueError( |
| 854 | 'State ' + str(i) + ' is incompatible with layer ' + |
| 855 | self.name + ': expected shape=' + str( |
| 856 | (batch_size, state)) + ', found shape=' + str(value.shape)) |
| 857 | set_value_tuples.append((state, value)) |
| 858 | K.batch_set_value(set_value_tuples) |
| 859 | |
| 860 | def get_config(self): |
| 861 | config = { |