LoginSignup
0
1

More than 3 years have passed since last update.

pythonをストレスなく使う!(pydocが便利、マイブーム。例:python -m pydoc PIL.Image.Image.resize)

Last updated at Posted at 2020-02-01

目的

 pythonをストレスなく使う!
そのためには、少しでも、理解のレベルを上げる必要あり。
なんでも、こだわって、、、、理解を深める。
ここで記載しているのは、

pydocが便利、マイブーム。例:python -m pydoc PIL.Image.Image.resize

です。

関数とかの仕様を調べる際に、ぐぐるとかいろんな方法があると思いますが、
簡単なことであれば、
ここに示す、pydocで、目的が達成されることが、
体感としては、3割ぐらいあります。
便利です。

例の2として、
python -m pydoc keras.models.Model.predict
示しました。

例の3として
python -m pydoc tf_explain.core.grad_cam.GradCAM
示しました。実益ありました(=知りたいことが、すぱっとわかりました。)、この例は。

 使い方の例1

(少し、前提説明は、省略しますが、)

Image.fromarray(arr).resize()

の仕様を調べたいと考えた際に、

python -m pydoc PIL.Image.Image.resize

という風に、pydocを使うと、以下の結果が得られます。

C:\_temp_work>python -m pydoc PIL.Image.Image.resize
Help on function resize in PIL.Image.Image:

PIL.Image.Image.resize = resize(self, size, resample=0, box=None)
    Returns a resized copy of this image.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height). <--★これが調べたかったこと
    :param resample: An optional resampling filter.  This can be
       one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,
       :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,
       :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.
       If omitted, or if the image has mode "1" or "P", it is
       set :py:attr:`PIL.Image.NEAREST`.
       See: :ref:`concept-filters`.
    :param box: An optional 4-tuple of floats giving the region
       of the source image which should be scaled.
       The values should be within (0, 0, width, height) rectangle.
       If omitted or None, the entire source is used.
    :returns: An :py:class:`~PIL.Image.Image` object.


C:\_temp_work>


上記において、

PIL.Image.Image.

と書けばいいのが、わからないケースがあると思います。
その場合は、一旦、途中までで、

C:\_temp_work>python -m pydoc PIL.Image.fromarray
Help on function fromarray in PIL.Image:

PIL.Image.fromarray = fromarray(obj, mode=None)
    Creates an image memory from an object exporting the array interface
    (using the buffer protocol).

    If **obj** is not contiguous, then the tobytes method is called
    and :py:func:`~PIL.Image.frombuffer` is used.

    If you have an image in NumPy::

      from PIL import Image
      import numpy as np
      im = Image.open('hopper.jpg')
      a = np.asarray(im)

    Then this can be used to convert it to a Pillow image::

      im = Image.fromarray(a)

    :param obj: Object with array interface
    :param mode: Mode to use (will be determined from type if None)
      See: :ref:`concept-modes`.
    :returns: An image object. <--★残念、誤記。正解、大文字スタートImageです。

    .. versionadded:: 1.1.6

とかすれば、戻りの型とかがわかると思います。

 使い方の例2

以下は、kerasのpredictの仕様を調べた例。
通常のサイトでも調査できるが、バージョンとかの違いが発生するかもしれず、今、動いているコード
で調べられるのは、いいときもある?

C:\_qiita>python -m pydoc keras.models.Model.predict
Using TensorFlow backend.
Help on function predict in keras.models.Model:

keras.models.Model.predict = predict(self, x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False)
    Generates output predictions for the input samples.

    Computation is done in batches.

    # Arguments
        x: Input data. It could be:
            - A Numpy array (or array-like), or a list of arrays
              (in case the model has multiple inputs).
            - A dict mapping input names to the corresponding
              array/tensors, if the model has named inputs.
            - A generator or `keras.utils.Sequence` returning
              `(inputs, targets)` or `(inputs, targets, sample weights)`.
            - None (default) if feeding from framework-native
              tensors (e.g. TensorFlow data tensors).
        batch_size: Integer or `None`.
            Number of samples per gradient update.
            If unspecified, `batch_size` will default to 32.
            Do not specify the `batch_size` is your data is in the
            form of symbolic tensors, generators, or
            `keras.utils.Sequence` instances (since they generate batches).
        verbose: Verbosity mode, 0 or 1.
        steps: Total number of steps (batches of samples)
            before declaring the prediction round finished.
            Ignored with the default value of `None`.
        callbacks: List of `keras.callbacks.Callback` instances.
            List of callbacks to apply during prediction.
            See [callbacks](/callbacks).
        max_queue_size: Integer. Used for generator or `keras.utils.Sequence`
            input only. Maximum size for the generator queue.
            If unspecified, `max_queue_size` will default to 10.
        workers: Integer. Used for generator or `keras.utils.Sequence` input
            only. Maximum number of processes to spin up when using
            process-based threading. If unspecified, `workers` will default
            to 1. If 0, will execute the generator on the main thread.
        use_multiprocessing: Boolean. Used for generator or
            `keras.utils.Sequence` input only. If `True`, use process-based
            threading. If unspecified, `use_multiprocessing` will default to
            `False`. Note that because this implementation relies on
            multiprocessing, you should not pass non-picklable arguments to
            the generator as they can't be passed easily to children processes.

    # Returns
        Numpy array(s) of predictions.

    # Raises
        ValueError: In case of mismatch between the provided
            input data and the model's expectations,
            or in case a stateful model receives a number of samples
            that is not a multiple of the batch size.


C:\_qiita>
C:\_qiita>

使い方の例3

以下は、tf_explainのexplainの仕様を調べた例。
image_weightという引数が知りたかった。 役立った!

C:\_>python -m pydoc tf_explain.core.grad_cam.GradCAM
Help on class GradCAM in tf_explain.core.grad_cam:

tf_explain.core.grad_cam.GradCAM = class GradCAM(builtins.object)
 |  Perform Grad CAM algorithm for a given input
 |
 |  Paper: [Grad-CAM: Visual Explanations from Deep Networks
 |          via Gradient-based Localization](https://arxiv.org/abs/1610.02391)
 |
 |  Methods defined here:
 |
 |  explain(self, validation_data, model, class_index, layer_name=None, colormap=16, image_weight=0.7)
 |      Compute GradCAM for a specific class index.
 |
 |      Args:
 |          validation_data (Tuple[np.ndarray, Optional[np.ndarray]]): Validation data
 |              to perform the method on. Tuple containing (x, y).
 |          model (tf.keras.Model): tf.keras model to inspect
 |          class_index (int): Index of targeted class
 |          layer_name (str): Targeted layer for GradCAM. If no layer is provided, it is
 |              automatically infered from the model architecture.
 |          colormap (int): OpenCV Colormap to use for heatmap visualization
 |          image_weight (float): An optional `float` value in range [0,1] indicating the weight of
 |              the input image to be overlaying the calculated attribution maps. Defaults to `0.7`.
 |
 |      Returns:
 |          numpy.ndarray: Grid of all the GradCAM
 |
 |  save(self, grid, output_dir, output_name)
 |      Save the output to a specific dir.
-- More  --


自分でアンチな事例

データ(属性)の情報まで表示しようとすると、ひどいことになる。
以下は、
sys.executable
を調べようとして、
str
の説明をみせられている。

C:\_qiita>python -m pydoc sys.executable
Help on str in sys object:

sys.executable = class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |
 |  __ge__(self, value, /)


C:\_qiita>


関連(本人)

 直接関係あり

pythonをストレスなく使う!(docとhelp)
深層学習とかでのPythonエラー「AttributeError: module 'scipy.misc' has no attribute 'imresize'」への対処

 直接関係なし

pythonをストレスなく使う!(Pythonでは、すべてがオブジェクトとして実装されている)
pythonをストレスなく使う!(Pylintに寄り添う)
pythonをストレスなく使う!(ExpressionとStatement)
英語と日本語、両方使ってPythonを丁寧に学ぶ。

今後

コメントなどあればお願いします。
(以前、別の記事でpydocの存在を教えて頂きました。それで、この記事につながっているので、、、、)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1