Skip to content

Instantly share code, notes, and snippets.

@takatakamanbou
Created May 11, 2020 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takatakamanbou/6213ee3062e7d346d82e65ae2615887d to your computer and use it in GitHub Desktop.
Save takatakamanbou/6213ee3062e7d346d82e65ae2615887d to your computer and use it in GitHub Desktop.
PIP2020-hw05.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "PIP2020-hw05.ipynb",
"provenance": [],
"collapsed_sections": [
"2Nuoadmu_XyS"
],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/takatakamanbou/6213ee3062e7d346d82e65ae2615887d/pip2020-hw05.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NI3mY1FGZWgV",
"colab_type": "text"
},
"source": [
"# 2020年度パターン情報処理第5回宿題\n",
"この科目のウェブサイトへ https://www-tlab.math.ryukoku.ac.jp/wiki/?PIP/2020"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ffaGVK2o5VWe",
"colab_type": "text"
},
"source": [
"## はじめに\n",
"\n",
"左上の「三」みたいなの(より正確には,「・ー」が3本)をクリックすると,目次が開きます."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0IpujRN_Wuib",
"colab_type": "text"
},
"source": [
"### これは何?\n",
"\n",
"これは,Google Colaboratory(以下 Google Colab) という,Google が提供しているサービスを利用して作成した資料です.Notebook と呼びます.クラウド上に仮想的に構築された Linux マシン上で Python のプログラムを実行することができます."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dFELLpn2Wybq",
"colab_type": "text"
},
"source": [
"↓の箱(セルと呼びます)をクリックして,左端の再生ボタンみたいなのを押すか,Shift+Enter(シフトキーを押しながらエンターキーを押す)してみましょう."
]
},
{
"cell_type": "code",
"metadata": {
"id": "aF6mM2cxTpho",
"colab_type": "code",
"colab": {}
},
"source": [
"x = 5963\n",
"y = 1314\n",
"x + y"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "vtr_I1RuUMc1",
"colab_type": "text"
},
"source": [
"↑が実行できたら,さらに次のことをやろう\n",
"* 上記の x + y を x - y に変更して実行(再生ボタン or Shift+Enter)してみよう\n",
"* 数字や式をいじって実行してみよう\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "5qOF9FaDZP-1",
"colab_type": "code",
"colab": {}
},
"source": [
"# おまけ: Python の for 文の例 (1)\n",
"for i in range(5):\n",
" print(i, i*i)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "IlB4q76EZkTq",
"colab_type": "code",
"colab": {}
},
"source": [
"# おまけ: Python の for 文の例 (2)\n",
"for x in [ 1, 2, 99, 'hoge', [1,2,3]]:\n",
" print(x)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "QRNjWashW4pr",
"colab_type": "text"
},
"source": [
"### Notebook の動かし方に関する注意\n",
"\n",
"この Notebook では,上の方のセルで作った変数や関数を後のセルで使うことがあります.そのため,上の方のセルを実行せずに下の方を実行すると,エラーになることがあります.上から順に実行していきましょう.\n",
"\n",
"また,メニューの「ランタイム」から,「すべてのセルを実行」したりすることも可能です.セルの実行が終わらなくなったりした場合は,「ランライム」 > 「実行を中断」. "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1jfSXIY6VNxP",
"colab_type": "text"
},
"source": [
"### 準備\n",
"\n",
"以下のプログラムを実行するための準備です.このセルを実行してから,先へ進みましょう."
]
},
{
"cell_type": "code",
"metadata": {
"id": "IFYQk7ONZENz",
"colab_type": "code",
"colab": {}
},
"source": [
"# 科学技術計算のライブラリ NumPy のモジュールを np という名前で使えるようにする\n",
"import numpy as np\n",
"# グラフを描くためのライブラリ matplotlib の pyplot を plt という名前でインポート\n",
"import matplotlib.pyplot as plt\n",
"# コンピュータビジョン・画像処理のライブラリ OpenCV のモジュールをインポート\n",
"#import cv2 # 今回使ってない"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "bUpNOXqZZnPU",
"colab_type": "text"
},
"source": [
"## ★ 5.3 離散コサイン変換 / ★ 5.4 直交展開とデータ圧縮"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "l2maN_Ri9RuM",
"colab_type": "text"
},
"source": [
"### 離散コサイン変換の正規直交基底を作ろう"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ueWvaKQGv04A",
"colab_type": "text"
},
"source": [
"<参考: 第5回講義資料>\n",
"\n",
"$N$ 次元ベクトル $\\mathbf{e}_{k}$ ($k=0,1,\\ldots , N-1$) を次のように定めると,$\\{ \\mathbf{e}_{0}, \\mathbf{e}_{1}, \\dots , \\mathbf{e}_{N-1}\\}$ は正規直交基底となる.\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{e}_{0} &= \\sqrt{\\frac{1}{N}}\n",
"\\left(\n",
"1,1, \\dots , 1\n",
"\\right) \\\\\n",
"\\mathbf{e}_{k} &= \\sqrt{\\frac{2}{N}} \n",
"\\left(\n",
"\\cos{\\frac{\\pi k}{2N}}, \n",
"\\cos{\\frac{3 \\pi k}{2N}}, \\dots ,\n",
"\\cos{\\frac{(2N-1)\\pi k}{2N}} \n",
"\\right) \\quad (k = 1, \\dots , N-1)\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"したがって,$\\{ \\mathbf{e}_{k} \\}$ を用いると,任意の$N$次元実ベクトル $\\mathbf{f} = (f_{0}, f_{1}, \\dots , f_{N-1})$ を次式のように一意に展開できる.\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{f} = c_{0}\\mathbf{e}_{0} + c_{1}\\mathbf{e}_{1} + \\dots + c_{N-1}\\mathbf{e}_{N-1}\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"ただし,展開係数 $c_{k}$ は $c_{k} = \\mathbf{f}\\cdot\\mathbf{e}_{k}$ で与えられる.$\\mathbf{f}$ から $c_{0},c_{1},\\dots ,c_{N-1}$ を求める演算を離散コサイン変換という."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ml0I4EWc7oil",
"colab_type": "text"
},
"source": [
"↓は,DCTの正規直交基底を作る関数を定義するセルである.実行してから先へ進もう."
]
},
{
"cell_type": "code",
"metadata": {
"id": "83EVKc3UZR8f",
"colab_type": "code",
"colab": {}
},
"source": [
"# DCT の正規直交基底を作る関数\n",
"#\n",
"def getDCTbasis(N):\n",
" \n",
" basis = np.empty((N, N)) # 空の N x N 行列\n",
" basis[0, :] = 1.0 / np.sqrt(N) # 0行目 = 0番目の基底ベクトル\n",
" for k in range(1, N): # k = 1, 2, ..., N-1\n",
" x = np.arange(1, 2*N, 2) # 奇数列 1, 3, ..., 2N-1\n",
" y = np.pi * x * k / (2*N) # cos の中身\n",
" basis[k, :] = np.cos(y) * np.sqrt(2/N)\n",
" \n",
" return basis"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "jkZmnJEl7yhi",
"colab_type": "text"
},
"source": [
"#### $N =4$ の例 \n",
"\n",
"順番にセルを実行しよう.セルとセルの間の文や,セルの中に書かれたコメント(「`#`」以降の部分)に注意."
]
},
{
"cell_type": "code",
"metadata": {
"id": "lAoDuCfacbXd",
"colab_type": "code",
"colab": {}
},
"source": [
"# 4次元のDCT基底を作って変数 dct に代入\n",
"N = 4\n",
"dct = getDCTbasis(N)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "MoIGqJ4qcygt",
"colab_type": "code",
"colab": {}
},
"source": [
"# 0番目の基底ベクトル\n",
"print(dct[0])"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "NB2mXTNp8pv8",
"colab_type": "text"
},
"source": [
"以下のセルを実行したのち,「修正 → 実行」を何度か繰り返して,$\\mathbf{e}_1$ や $\\mathbf{e}_2$ の値を確認しなさい."
]
},
{
"cell_type": "code",
"metadata": {
"id": "fdekgOyrcqjz",
"colab_type": "code",
"colab": {}
},
"source": [
"print(dct[1])"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "6UM8sl7Y9yG-",
"colab_type": "text"
},
"source": [
"##### Q.1 以下の「★ ここから」から「★ ここまで」までの部分のセルを実行し,何を計算しているか,何を確認しているか,を考えなさい.\n",
"\n",
"**★ ここから**\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "IxBsAKbUcw77",
"colab_type": "code",
"colab": {}
},
"source": [
"# dct[0] と dct[1] の内積.'@'はベクトル同士の内積や行列同士の積を表す演算子\n",
"dct[0] @ dct[1]"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "3fw99gm5dFwf",
"colab_type": "code",
"colab": {}
},
"source": [
"dct[0] @ dct[2] # [ ]の中の数を変えて他の場合についても計算させてみよう"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "RVqAbRvKdLFG",
"colab_type": "code",
"colab": {}
},
"source": [
"dct[0] @ dct[0] # [ ]の中の数を変えて他の場合についても計算させてみよう"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "4a51CJU9-wZv",
"colab_type": "text"
},
"source": [
"**★ ここまで**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "_ffKL_RfdOJl",
"colab_type": "code",
"colab": {}
},
"source": [
"# 行列 dct の k 行目が k番目の基底ベクトルなので, dct と dct の転置行列の積の (i, j) 要素は dct[i] と dct[j] の内積になる\n",
"print(dct @ dct.T)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "dGv19G3s9-r7",
"colab_type": "text"
},
"source": [
"#### $N = 16$ の例"
]
},
{
"cell_type": "code",
"metadata": {
"id": "iO58-6a3joSs",
"colab_type": "code",
"colab": {}
},
"source": [
"# 16次元の例\n",
"N = 16\n",
"dct = getDCTbasis(N)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "OXTHnx1t-F9r",
"colab_type": "code",
"colab": {}
},
"source": [
"print(dct[0]) # [ ]の中の数を変えて他の場合についても出力させてみよう"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "NDmPDMGbf12r",
"colab_type": "code",
"colab": {}
},
"source": [
"# いくつかの基底ベクトルの要素を折れ線グラフとして描いてみる\n",
"X = np.arange(0, N) # 横軸の値\n",
"fig, ax = plt.subplots(facecolor=\"white\", figsize=(8, 6))\n",
"ax.plot(X, dct[0], \"-o\", label = \"dct[0]\")\n",
"#ax.plot(X, dct[1], \"-o\", label = \"dct[1]\")\n",
"#ax.plot(X, dct[2], \"-o\", label = \"dct[2]\")\n",
"#ax.plot(X, dct[3], \"-o\", label = \"dct[3]\") # 行頭の # をはずして再実行してみよう\n",
"#ax.plot(X, dct[15], \"-o\", label = \"dct[15]\")\n",
"ax.legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "JjmygZym-blY",
"colab_type": "text"
},
"source": [
"##### Q.2 上記のグラフは何を描いたものか考えなさい."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b4ZElzy3_4-u",
"colab_type": "text"
},
"source": [
"### 信号を展開・近似してみよう"
]
},
{
"cell_type": "code",
"metadata": {
"id": "gkxZHWRzjNCh",
"colab_type": "code",
"colab": {}
},
"source": [
"# 16次元のDCT基底を求める\n",
"N = 16\n",
"dct = getDCTbasis(N)\n",
"\n",
"# 講義資料の16次元ベクトルの例\n",
"f = np.array( [0, 0, 0, 0, 10, 10, 10, 10, 8, 6, 4, 2, 0, 0, 0, 0], dtype = float)\n",
"print(f)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "8LWqJNR1Ax1A",
"colab_type": "code",
"colab": {}
},
"source": [
"fig, ax = plt.subplots(facecolor=\"white\", figsize=(8, 6))\n",
"ax.plot(X, f, \"-o\", label = \"f\")\n",
"ax.legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "f5RzSD2y-x0v",
"colab_type": "text"
},
"source": [
"上記の $\\mathbf{f}$ は\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{f} = c_{0}\\mathbf{e}_{0} + c_{1}\\mathbf{e}_{1} + \\dots + c_{15}\\mathbf{e}_{15}\n",
"\\end{aligned}\n",
"$$\n",
"と展開できて,展開係数 $c_{k}$ は $c_{k} = \\mathbf{f}\\cdot\\mathbf{e}_{k}$ で与えられる."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dJcCTs8W-4In",
"colab_type": "text"
},
"source": [
"$c_0 = \\mathbf{f} \\cdot \\mathbf{e}_0$ を計算してみる."
]
},
{
"cell_type": "code",
"metadata": {
"id": "n-_1d_JEA6dI",
"colab_type": "code",
"colab": {}
},
"source": [
"# 0番目の展開係数\n",
"f @ dct[0]"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "7pgNYASP_FQY",
"colab_type": "code",
"colab": {}
},
"source": [
"f @ dct[1] # 適当にいじって,他の展開係数の値も計算してみよう"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "nl1_JZm4BMVt",
"colab_type": "code",
"colab": {}
},
"source": [
"# N 個の展開係数を一気に計算\n",
"coeff = dct @ f\n",
"print(coeff)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "6E7G7c4P_KU-",
"colab_type": "text"
},
"source": [
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{f} = c_{0}\\mathbf{e}_{0} + c_{1}\\mathbf{e}_{1} + \\dots + c_{15}\\mathbf{e}_{15}\n",
"\\end{aligned}\n",
"$$\n",
"に対して,展開を $k = 3$ までで打ち切ったもの\n",
"$$\n",
"\\begin{aligned}\n",
"\\widetilde{\\mathbf{f}} = c_{0}\\mathbf{e}_{0} + c_{1}\\mathbf{e}_{1} + c_{2}\\mathbf{e}_{2}+ c_{3}\\mathbf{e}_{3}\n",
"\\end{aligned}\n",
"$$\n",
"を考えてみる."
]
},
{
"cell_type": "code",
"metadata": {
"id": "MUyxRAGfBrjp",
"colab_type": "code",
"colab": {}
},
"source": [
"# 3番目までで展開を打ち切ってみる\n",
"ft = coeff[0] * dct[0] + coeff[1] * dct[1] + coeff[2] * dct[2] + coeff[3] * dct[3]\n",
"print(ft)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "VbTzpQUzCXig",
"colab_type": "code",
"colab": {}
},
"source": [
"# オリジナルの信号 (f) とあわせて ft のグラフを描いてみる\n",
"fig, ax = plt.subplots(facecolor=\"white\", figsize=(8, 6))\n",
"ax.plot(X, f, \"-o\", label = \"f\")\n",
"ax.plot(X, ft, \"-o\", label = \"ft\")\n",
"ax.legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "QDxS25wCCo8l",
"colab_type": "code",
"colab": {}
},
"source": [
"# 同じことを行列の計算として考えるともっと簡単に書ける\n",
"H = 4\n",
"ft = coeff[:H] @ dct[:H, :] \n",
"print(ft)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "Kk8Tu9JxEYqk",
"colab_type": "code",
"cellView": "both",
"colab": {}
},
"source": [
"#@title スライダを動かすと H (いくつの基底ベクトルをつかうか)を変えて近似させられます.H を大きくするとどうなるでしょう? { run: \"auto\" }\n",
"H = 1 #@param {type:\"slider\", min:1, max:16, step:1}\n",
"ft = coeff[:H] @ dct[:H, :]\n",
"fig, ax = plt.subplots(facecolor=\"white\", figsize=(8, 6))\n",
"ax.plot(X, f, \"-o\", label = \"f\")\n",
"ax.plot(X, ft, \"-o\", label = \"ft (H = {})\".format(H))\n",
"ax.legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "2Nuoadmu_XyS",
"colab_type": "text"
},
"source": [
"##### Q.3 スライダを動かして H いろいろ変えるとどうのような変化があるか観察しなさい."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ODmaA8Y4AJ-A",
"colab_type": "text"
},
"source": [
"この Colab Notebook はここまでです.次は,この科目の Moodle コースへ行って,「ex05 宿題」をやりましょう.\n",
"- https://moodle.media.ryukoku.ac.jp/course/view.php?id=2242\n",
"- https://www-tlab.math.ryukoku.ac.jp/wiki/?PIP/2020\n",
"- https://www-tlab.math.ryukoku.ac.jp/wiki/?PIP/2020/ex05\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "edzGqC-eAu32",
"colab_type": "text"
},
"source": [
"## おまけ"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "B1_RMhi5BJL1",
"colab_type": "text"
},
"source": [
"### Colab Notebook を自分の Google Drive 上に保存する\n",
"\n",
"いじった Colab Notebook を残しておきたい場合,次のようにすると,自分の Google Drive 上へ保存できます.\n",
"\n",
"1. 自分の Google アカウント(学籍番号@mail.ryukoku.ac.jpのでもよいし,個人のでもよい)でログインした状態で,この Notebook を開く\n",
"1. 「ファイル」 > 「ドライブにコピーを保存」とすると,ブラウザの画面が切り替わり,「hoge.ipynb のコピー」のような名前の Colab Notebook が開いた状態になる.\n",
"1. その画面で「ファイル」 > 「ドライブで探す」とすると,コピーしたファイルが,GoogleDriveの\n",
"```\n",
"「マイドライブ」 > 「Colab Notebooks」\n",
"```\n",
"にあることがわかる.\n",
"1. ファイル名に「のコピー」がついたままなのは気持ちわるいので,適当に変更.拡張子は .ipynb で.\n",
"1. 好きにいじる.\n",
"1. 適宜「ファイル」 > 「保存」 する.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iy0aW4e5DswI",
"colab_type": "text"
},
"source": [
"### Colab について知りたい\n",
"\n",
"Google Colab について知りたいひとは,Google の Colab 紹介ページへどうぞ: https://colab.research.google.com/?hl=ja これ自身が Colab のページです.\n",
"\n",
"Google Colab は,Jupyter Notebook をもとに作られています.**Jupyter Notebook** は,自分のPC上でPythonなどのプログラムを対話的に実行できる「ノートブック」を,ブラウザからアクセスできる仕組みです.最近は,Python 以外の様々な言語に対応しています.\n",
"\n",
"いろいろググって調べてみるとよいでしょう.\n",
"\n",
"そのうちどこかに,自分のPCにPythonとかJupyter関係とかインストール方法を説明する資料を作りたい...."
]
},
{
"cell_type": "code",
"metadata": {
"id": "Bz4l96UxGLJE",
"colab_type": "code",
"colab": {}
},
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "eAZAVIn0F5KD",
"colab_type": "text"
},
"source": [
"### 猫出したい?コーギー出したい?"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ew4xCbvZGJNu",
"colab_type": "text"
},
"source": [
"「ツール」 > 「設定」 > 「その他」"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment