0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonの下準備

Last updated at Posted at 2021-07-11

Pythonの実行環境はGoogle Colaboratoryの利用を想定。
本記事ではPythonを利用する際の下準備部分の情報について記述する。
主な内容は以下の通り。

  • Google Colaboratoryの機能
  • ライブラリのインストールについて
  • Pythonの構文など

Google Colaboratory ショートカット

# Markdownモードへ変更
[Ctrl] + [M] + [M]
# Codeモードへ変更
[Ctrl] + [M] + [Y]
# セルを上に追加
[Ctrl] + [M] + [A]
# セルを下に追加
[Ctrl] + [M] + [B]
# セルのコピー
[Ctrl] + [M] + [C]
# セルの貼り付け
[Ctrl] + [M] + [V]
# セルの消去
[Ctrl] + [M] + [D]
# コメントアウト
[Ctrl] + [/]

Python 環境構築

# ライブラリをverson指定してインストール
pip install torch==1.7.0+cu101
# 最新バージョンへ更新
pip install --upgrade torch
# バージョンの確認
pip show torch
# 一括Update
pip list -o | awk 'NR>2{print$1}' | xargs pip install -U

# Windowsにwheel形式でインストールする方法
# 1.wheel形式を扱える様にwheelをインストール
pip install wheel
# 2.各ライブラリの公式サイトからwheel形式のファイルをダウンロード
# 3.ダウンロードしたライブラリをインストール
pip install '***.whl'

基本的な構文の備忘録

# print記述方法
print('{}, {}, {}'.format(1, 2, 3))
print('{0}, {1}, {2}'.format(1, 2, 3))
print('{a}, {b}, {c}'.format(a=1, b=2, c=3))
print('{a}, {b}, {c}'.format(**{'a':1, 'b':2, 'c':3}))

# 小数点四捨五入(小数点3桁表示の場合)
print('小数点4桁目四捨五入結果:{:.3f}'.format(0.15555))
 # printの中でformat(0.15555, '.3f')の様に指定しても四捨五入されない

# リスト内包表記
j = [i + 1 for i in range(5)] # [1, 2, 3, 4, 5]

# Tensor型値抽出例
a = torch.Tensor([1., 2., 3.])
print(a[0].item())

# dict 属性を持つオブジェクトの、 dict 属性を返す。
vars(obj)

デバッグ

Google Colaboratoryのデバッグでは、%debugというマジックコマンドが使用可能。
標準のデバッグツールであるpdbを起動する。
セルごとで分けて実行が出来る為、あまり使用する場面はなさそう。

主なコマンド

  • Pdb().set_trace():ブレークポイント
  • h:ヘルプ
  • p: [expression]:式を評価して出力する
  • s:ステップイン(行単位で実行)
  • n:ステップオーバー(行単位で実行)
  • c:次のブレークポイントへ
  • q:その場で終了する

用語

  • wheel形式
    Pythonのパッケージの形式(フォーマット)のことを指す。実態はzip形式のアーカイブ。

  • シード
    シードは乱数の元になるもので、Pythonの環境を最初に実行した時に時刻などで初期化される。
    シードを固定することで再現性のある同じ乱数列(結果の連なり)を作ることが可能。

  • マジックコマンド
    JupyterLabやIPythonで用意されている関数群

  • %lsmagic:コマンドのリスト

  • %magic:マニュアル

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?