| Total Complexity | 41 |
| Total Lines | 365 |
| Duplicated Lines | 0 % |
Complex classes like blocks.bricks.Brick often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import inspect |
||
| 411 | @add_metaclass(_Brick) |
||
| 412 | class Brick(Annotation): |
||
| 413 | """A brick encapsulates Theano operations with parameters. |
||
| 414 | |||
| 415 | A brick goes through the following stages: |
||
| 416 | |||
| 417 | 1. Construction: The call to :meth:`__init__` constructs a |
||
| 418 | :class:`Brick` instance with a name and creates any child bricks as |
||
| 419 | well. |
||
| 420 | 2. Allocation of parameters: |
||
| 421 | |||
| 422 | a) Allocation configuration of children: The |
||
| 423 | :meth:`push_allocation_config` method configures any children of |
||
| 424 | this block. |
||
| 425 | b) Allocation: The :meth:`allocate` method allocates the shared |
||
| 426 | Theano variables required for the parameters. Also allocates |
||
| 427 | parameters for all children. |
||
| 428 | |||
| 429 | 3. The following can be done in either order: |
||
| 430 | |||
| 431 | a) Application: By applying the brick to a set of Theano |
||
| 432 | variables a part of the computational graph of the final model is |
||
| 433 | constructed. |
||
| 434 | b) The initialization of parameters: |
||
| 435 | |||
| 436 | 1. Initialization configuration of children: The |
||
| 437 | :meth:`push_initialization_config` method configures any |
||
| 438 | children of this block. |
||
| 439 | 2. Initialization: This sets the initial values of the |
||
| 440 | parameters by a call to :meth:`initialize`, which is needed |
||
| 441 | to call the final compiled Theano function. Also initializes |
||
| 442 | all children. |
||
| 443 | |||
| 444 | Not all stages need to be called explicitly. Step 3(a) will |
||
| 445 | automatically allocate the parameters if needed. Similarly, step |
||
| 446 | 3(b.2) and 2(b) will automatically perform steps 3(b.1) and 2(a) if |
||
| 447 | needed. They only need to be called separately if greater control is |
||
| 448 | required. The only two methods which always need to be called are an |
||
| 449 | application method to construct the computational graph, and the |
||
| 450 | :meth:`initialize` method in order to initialize the parameters. |
||
| 451 | |||
| 452 | At each different stage, a brick might need a certain set of |
||
| 453 | configuration settings. All of these settings can be passed to the |
||
| 454 | :meth:`__init__` constructor. However, by default many bricks support |
||
| 455 | *lazy initialization*. This means that the configuration settings can |
||
| 456 | be set later. |
||
| 457 | |||
| 458 | .. note:: |
||
| 459 | |||
| 460 | Some arguments to :meth:`__init__` are *always* required, even when |
||
| 461 | lazy initialization is enabled. Other arguments must be given before |
||
| 462 | calling :meth:`allocate`, while others yet only need to be given in |
||
| 463 | order to call :meth:`initialize`. Always read the documentation of |
||
| 464 | each brick carefully. |
||
| 465 | |||
| 466 | Lazy initialization can be turned off by setting ``Brick.lazy = |
||
| 467 | False``. In this case, there is no need to call :meth:`initialize` |
||
| 468 | manually anymore, but all the configuration must be passed to the |
||
| 469 | :meth:`__init__` method. |
||
| 470 | |||
| 471 | Parameters |
||
| 472 | ---------- |
||
| 473 | name : str, optional |
||
| 474 | The name of this brick. This can be used to filter the application |
||
| 475 | of certain modifications by brick names. By default, the brick |
||
| 476 | receives the name of its class (lowercased). |
||
| 477 | |||
| 478 | Attributes |
||
| 479 | ---------- |
||
| 480 | name : str |
||
| 481 | The name of this brick. |
||
| 482 | print_shapes : bool |
||
| 483 | ``False`` by default. If ``True`` it logs the shapes of all the |
||
| 484 | input and output variables, which can be useful for debugging. |
||
| 485 | parameters : list of :class:`~tensor.TensorSharedVariable` and ``None`` |
||
| 486 | After calling the :meth:`allocate` method this attribute will be |
||
| 487 | populated with the shared variables storing this brick's |
||
| 488 | parameters. Allows for ``None`` so that parameters can always be |
||
| 489 | accessed at the same index, even if some parameters are only |
||
| 490 | defined given a particular configuration. |
||
| 491 | children : list of bricks |
||
| 492 | The children of this brick. |
||
| 493 | allocated : bool |
||
| 494 | ``False`` if :meth:`allocate` has not been called yet. ``True`` |
||
| 495 | otherwise. |
||
| 496 | initialized : bool |
||
| 497 | ``False`` if :meth:`allocate` has not been called yet. ``True`` |
||
| 498 | otherwise. |
||
| 499 | allocation_config_pushed : bool |
||
| 500 | ``False`` if :meth:`allocate` or :meth:`push_allocation_config` |
||
| 501 | hasn't been called yet. ``True`` otherwise. |
||
| 502 | initialization_config_pushed : bool |
||
| 503 | ``False`` if :meth:`initialize` or |
||
| 504 | :meth:`push_initialization_config` hasn't been called yet. ``True`` |
||
| 505 | otherwise. |
||
| 506 | |||
| 507 | Notes |
||
| 508 | ----- |
||
| 509 | To provide support for lazy initialization, apply the :meth:`lazy` |
||
| 510 | decorator to the :meth:`__init__` method. |
||
| 511 | |||
| 512 | Brick implementations *must* call the :meth:`__init__` constructor of |
||
| 513 | their parent using `super(BlockImplementation, |
||
| 514 | self).__init__(**kwargs)` at the *beginning* of the overriding |
||
| 515 | `__init__`. |
||
| 516 | |||
| 517 | The methods :meth:`_allocate` and :meth:`_initialize` need to be |
||
| 518 | overridden if the brick needs to allocate shared variables and |
||
| 519 | initialize their values in order to function. |
||
| 520 | |||
| 521 | A brick can have any number of methods which apply the brick on Theano |
||
| 522 | variables. These methods should be decorated with the |
||
| 523 | :func:`application` decorator. |
||
| 524 | |||
| 525 | If a brick has children, they must be listed in the :attr:`children` |
||
| 526 | attribute. Moreover, if the brick wants to control the configuration of |
||
| 527 | its children, the :meth:`_push_allocation_config` and |
||
| 528 | :meth:`_push_initialization_config` methods need to be overridden. |
||
| 529 | |||
| 530 | Examples |
||
| 531 | -------- |
||
| 532 | Most bricks have lazy initialization enabled. |
||
| 533 | |||
| 534 | >>> import theano |
||
| 535 | >>> from blocks.initialization import IsotropicGaussian, Constant |
||
| 536 | >>> from blocks.bricks import Linear |
||
| 537 | >>> linear = Linear(input_dim=5, output_dim=3, |
||
| 538 | ... weights_init=IsotropicGaussian(), |
||
| 539 | ... biases_init=Constant(0)) |
||
| 540 | >>> x = theano.tensor.vector() |
||
| 541 | >>> linear.apply(x) # Calls linear.allocate() automatically |
||
| 542 | linear_apply_output |
||
| 543 | >>> linear.initialize() # Initializes the weight matrix |
||
| 544 | |||
| 545 | """ |
||
| 546 | #: See :attr:`Brick.print_shapes` |
||
| 547 | print_shapes = False |
||
| 548 | |||
| 549 | def __init__(self, name=None): |
||
| 550 | if name is None: |
||
| 551 | name = self.__class__.__name__.lower() |
||
| 552 | self.name = name |
||
| 553 | |||
| 554 | self.children = [] |
||
| 555 | self.parents = [] |
||
| 556 | |||
| 557 | self.allocated = False |
||
| 558 | self.allocation_config_pushed = False |
||
| 559 | self.initialized = False |
||
| 560 | self.initialization_config_pushed = False |
||
| 561 | super(Brick, self).__init__() |
||
| 562 | |||
| 563 | def __repr__(self): |
||
| 564 | return repr_attrs(self, 'name') |
||
| 565 | |||
| 566 | @property |
||
| 567 | def parameters(self): |
||
| 568 | return self._parameters |
||
| 569 | |||
| 570 | @parameters.setter |
||
| 571 | def parameters(self, value): |
||
| 572 | self._parameters = Parameters(self, value) |
||
| 573 | |||
| 574 | @property |
||
| 575 | def children(self): |
||
| 576 | return self._children |
||
| 577 | |||
| 578 | @children.setter |
||
| 579 | def children(self, value): |
||
| 580 | self._children = Children(self, value) |
||
| 581 | |||
| 582 | def allocate(self): |
||
| 583 | """Allocate shared variables for parameters. |
||
| 584 | |||
| 585 | Based on the current configuration of this :class:`Brick` create |
||
| 586 | Theano shared variables to store the parameters. After allocation, |
||
| 587 | parameters are accessible through the :attr:`parameters` attribute. |
||
| 588 | |||
| 589 | This method calls the :meth:`allocate` method of all children |
||
| 590 | first, allowing the :meth:`_allocate` method to override the |
||
| 591 | parameters of the children if needed. |
||
| 592 | |||
| 593 | Raises |
||
| 594 | ------ |
||
| 595 | ValueError |
||
| 596 | If the configuration of this brick is insufficient to determine |
||
| 597 | the number of parameters or their dimensionality to be |
||
| 598 | initialized. |
||
| 599 | |||
| 600 | Notes |
||
| 601 | ----- |
||
| 602 | This method sets the :attr:`parameters` attribute to an empty list. |
||
| 603 | This is in order to ensure that calls to this method completely |
||
| 604 | reset the parameters. |
||
| 605 | |||
| 606 | """ |
||
| 607 | if hasattr(self, 'allocation_args'): |
||
| 608 | missing_config = [arg for arg in self.allocation_args |
||
| 609 | if getattr(self, arg) is NoneAllocation] |
||
| 610 | if missing_config: |
||
| 611 | raise ValueError('allocation config not set: ' |
||
| 612 | '{}'.format(', '.join(missing_config))) |
||
| 613 | if not self.allocation_config_pushed: |
||
| 614 | self.push_allocation_config() |
||
| 615 | for child in self.children: |
||
| 616 | if not child.allocated: |
||
| 617 | child.allocate() |
||
| 618 | self.parameters = [] |
||
| 619 | self._allocate() |
||
| 620 | self.allocated = True |
||
| 621 | |||
| 622 | def _allocate(self): |
||
| 623 | """Brick implementation of parameter initialization. |
||
| 624 | |||
| 625 | Implement this if your brick needs to allocate its parameters. |
||
| 626 | |||
| 627 | .. warning:: |
||
| 628 | |||
| 629 | This method should never be called directly. Call |
||
| 630 | :meth:`initialize` instead. |
||
| 631 | |||
| 632 | """ |
||
| 633 | pass |
||
| 634 | |||
| 635 | def initialize(self): |
||
| 636 | """Initialize parameters. |
||
| 637 | |||
| 638 | Intialize parameters, such as weight matrices and biases. |
||
| 639 | |||
| 640 | Notes |
||
| 641 | ----- |
||
| 642 | If the brick has not allocated its parameters yet, this method will |
||
| 643 | call the :meth:`allocate` method in order to do so. |
||
| 644 | |||
| 645 | """ |
||
| 646 | if hasattr(self, 'initialization_args'): |
||
| 647 | missing_config = [arg for arg in self.initialization_args |
||
| 648 | if getattr(self, arg) is NoneInitialization] |
||
| 649 | if missing_config: |
||
| 650 | raise ValueError('initialization config not set: ' |
||
| 651 | '{}'.format(', '.join(missing_config))) |
||
| 652 | if not self.allocated: |
||
| 653 | self.allocate() |
||
| 654 | if not self.initialization_config_pushed: |
||
| 655 | self.push_initialization_config() |
||
| 656 | for child in self.children: |
||
| 657 | if not child.initialized: |
||
| 658 | child.initialize() |
||
| 659 | self._initialize() |
||
| 660 | self.initialized = True |
||
| 661 | |||
| 662 | def _initialize(self): |
||
| 663 | """Brick implementation of parameter initialization. |
||
| 664 | |||
| 665 | Implement this if your brick needs to initialize its parameters. |
||
| 666 | |||
| 667 | .. warning:: |
||
| 668 | |||
| 669 | This method should never be called directly. Call |
||
| 670 | :meth:`initialize` instead. |
||
| 671 | |||
| 672 | """ |
||
| 673 | pass |
||
| 674 | |||
| 675 | def push_allocation_config(self): |
||
| 676 | """Push the configuration for allocation to child bricks. |
||
| 677 | |||
| 678 | Bricks can configure their children, based on their own current |
||
| 679 | configuration. This will be automatically done by a call to |
||
| 680 | :meth:`allocate`, but if you want to override the configuration of |
||
| 681 | child bricks manually, then you can call this function manually. |
||
| 682 | |||
| 683 | """ |
||
| 684 | self._push_allocation_config() |
||
| 685 | self.allocation_config_pushed = True |
||
| 686 | for child in self.children: |
||
| 687 | if not child.allocated: |
||
| 688 | try: |
||
| 689 | child.push_allocation_config() |
||
| 690 | except Exception: |
||
| 691 | self.allocation_config_pushed = False |
||
| 692 | raise |
||
| 693 | |||
| 694 | def _push_allocation_config(self): |
||
| 695 | """Brick implementation of configuring child before allocation. |
||
| 696 | |||
| 697 | Implement this if your brick needs to set the configuration of its |
||
| 698 | children before allocation. |
||
| 699 | |||
| 700 | .. warning:: |
||
| 701 | |||
| 702 | This method should never be called directly. Call |
||
| 703 | :meth:`push_allocation_config` instead. |
||
| 704 | |||
| 705 | """ |
||
| 706 | pass |
||
| 707 | |||
| 708 | def push_initialization_config(self): |
||
| 709 | """Push the configuration for initialization to child bricks. |
||
| 710 | |||
| 711 | Bricks can configure their children, based on their own current |
||
| 712 | configuration. This will be automatically done by a call to |
||
| 713 | :meth:`initialize`, but if you want to override the configuration |
||
| 714 | of child bricks manually, then you can call this function manually. |
||
| 715 | |||
| 716 | """ |
||
| 717 | self._push_initialization_config() |
||
| 718 | self.initialization_config_pushed = True |
||
| 719 | for child in self.children: |
||
| 720 | if not child.initialized: |
||
| 721 | try: |
||
| 722 | child.push_initialization_config() |
||
| 723 | except Exception: |
||
| 724 | self.initialization_config_pushed = False |
||
| 725 | raise |
||
| 726 | |||
| 727 | def _push_initialization_config(self): |
||
| 728 | """Brick implementation of configuring child before initialization. |
||
| 729 | |||
| 730 | Implement this if your brick needs to set the configuration of its |
||
| 731 | children before initialization. |
||
| 732 | |||
| 733 | .. warning:: |
||
| 734 | |||
| 735 | This method should never be called directly. Call |
||
| 736 | :meth:`push_initialization_config` instead. |
||
| 737 | |||
| 738 | """ |
||
| 739 | pass |
||
| 740 | |||
| 741 | def get_dim(self, name): |
||
| 742 | """Get dimension of an input/output variable of a brick. |
||
| 743 | |||
| 744 | Parameters |
||
| 745 | ---------- |
||
| 746 | name : str |
||
| 747 | The name of the variable. |
||
| 748 | |||
| 749 | """ |
||
| 750 | raise ValueError("No dimension information for {} available" |
||
| 751 | .format(name)) |
||
| 752 | |||
| 753 | def get_dims(self, names): |
||
| 754 | """Get list of dimensions for a set of input/output variables. |
||
| 755 | |||
| 756 | Parameters |
||
| 757 | ---------- |
||
| 758 | names : list |
||
| 759 | The variable names. |
||
| 760 | |||
| 761 | Returns |
||
| 762 | ------- |
||
| 763 | dims : list |
||
| 764 | The dimensions of the sources. |
||
| 765 | |||
| 766 | """ |
||
| 767 | return [self.get_dim(name) for name in names] |
||
| 768 | |||
| 769 | def get_unique_path(self): |
||
| 770 | """Returns unique path to this brick in the application graph.""" |
||
| 771 | if self.parents: |
||
| 772 | parent = min(self.parents, key=attrgetter('name')) |
||
| 773 | return parent.get_unique_path() + [self] |
||
| 774 | else: |
||
| 775 | return [self] |
||
| 776 | |||
| 957 |
This check looks for invalid names for a range of different identifiers.
You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.
If your project includes a Pylint configuration file, the settings contained in that file take precedence.
To find out more about Pylint, please refer to their site.