Jephian Lin
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 主成份分析 Principal component analysis ![Creative Commons License](https://i.creativecommons.org/l/by/4.0/88x31.png) This work by Jephian Lin is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/). $\newcommand{\trans}{^\top} \newcommand{\adj}{^{\rm adj}} \newcommand{\cof}{^{\rm cof}} \newcommand{\inp}[2]{\left\langle#1,#2\right\rangle} \newcommand{\dunion}{\mathbin{\dot\cup}} \newcommand{\bzero}{\mathbf{0}} \newcommand{\bone}{\mathbf{1}} \newcommand{\ba}{\mathbf{a}} \newcommand{\bb}{\mathbf{b}} \newcommand{\bc}{\mathbf{c}} \newcommand{\bd}{\mathbf{d}} \newcommand{\be}{\mathbf{e}} \newcommand{\bh}{\mathbf{h}} \newcommand{\bp}{\mathbf{p}} \newcommand{\bq}{\mathbf{q}} \newcommand{\br}{\mathbf{r}} \newcommand{\bx}{\mathbf{x}} \newcommand{\by}{\mathbf{y}} \newcommand{\bz}{\mathbf{z}} \newcommand{\bu}{\mathbf{u}} \newcommand{\bv}{\mathbf{v}} \newcommand{\bw}{\mathbf{w}} \newcommand{\tr}{\operatorname{tr}} \newcommand{\nul}{\operatorname{null}} \newcommand{\rank}{\operatorname{rank}} %\newcommand{\ker}{\operatorname{ker}} \newcommand{\range}{\operatorname{range}} \newcommand{\Col}{\operatorname{Col}} \newcommand{\Row}{\operatorname{Row}} \newcommand{\spec}{\operatorname{spec}} \newcommand{\vspan}{\operatorname{span}} \newcommand{\Vol}{\operatorname{Vol}} \newcommand{\sgn}{\operatorname{sgn}} \newcommand{\idmap}{\operatorname{id}} \newcommand{\am}{\operatorname{am}} \newcommand{\gm}{\operatorname{gm}} \newcommand{\mult}{\operatorname{mult}} \newcommand{\iner}{\operatorname{iner}}$ ```python from lingeo import random_int_list ``` ## Main idea Let $X$ be an $N\times d$ data matrix whose the sample vectors are centered at $\bzero\in\mathbb{R}^d$. Let $C = \frac{1}{N-1}X\trans X$ be the covariance matrix. Let $\bv$ be a unit vector in $\mathbb{R}^d$. One may project all data points onto the direction of $\bv$. Indeed, the projected data is $\bu = X\bv$. Thus, the mean of $\bu$ is $\inp{\bu}{\bone} = \bone\trans X\bu = \bzero\trans\bu = 0$, and the variance of $\bu$ is $\frac{1}{N-1}\inp{\bu}{\bu} = \frac{1}{N-1}\bu\trans X\trans X\bu = \bv\trans C\bv$. It is natural to consider the optimization problem: maximize $\bv\trans C\bv$, subject to $\|\bv\| = 1$. Let $\lambda_1\geq \cdots \geq \lambda_d$ be the eigenvalues of $C$ and $\{\bv_1,\ldots,\bv_d\}$ the corresponding orthonormal eigenbasis. According to the Rayleigh quotient theorem, the maximum is achieved by $\lambda_1$ when $\bv = \bv_1$. Therefore, $\bv_1$ is called the first **principal component** of the data, and one may continue to take $\bv_2,\bv_3,\ldots$ as the next principal components. ##### Algorithm (principal component analysis) Input: a data represented by an $N\times d$ matrix $X$ and the desired number $k$ of principal components Output: the principal components represented by the column vectors of a matrix $P$ 1. Let $J$ be the $N\times N$ all-ones matrix. Define $X_0 = (I - \frac{1}{n}J)X$. 2. Calculate the covariance matrix $C= \frac{1}{N-1}X_0\trans X_0$. 3. Find a diagonal matrix $D$, whose diagonal entries are $\lambda_1 \geq \cdots \geq \lambda_d$, and an orthogonal matrix $Q$ such that $C = QDQ\trans$. 3. Let $P$ be the $d\times k$ matrix obtained by the first $k$ columns of $Q$. A few points to emphasize: - The $Q$ matrix is the same as the $V$ in the algorithm in 606. - The eigenvalues $\lambda_1 \geq \cdots \geq \lambda_d$ are the variances when the data are projected onto the columns of $Q$. ## Side stories - explained variance ratio - `scipy.linalg.eigh` ## Experiments ##### Exercise 1 執行以下程式碼。 <!-- eng start --> Run the code below. <!-- eng end --> ```python ### code import numpy as np import matplotlib.pyplot as plt %matplotlib inline np.random.seed(0) print_ans = False mu = np.random.randint(-3,4, (2,)) cov = np.array([[1,1.9], [1.9,4]]) X = np.random.multivariate_normal(mu, cov, (20,)) mu = X.mean(axis=0) X0 = X - mu # u,s,vh = np.linalg.svd(X0) C = (1 / (19)) * X0.T.dot(X0) vals,vecs = np.linalg.eigh(C) vals = vals[::-1] vecs = vecs[:,::-1] P = vecs[:,:1] plt.axis('equal') plt.scatter(*X.T) plt.scatter(*mu, c="red") plt.arrow(*mu, *(vecs[:,0]), head_width=0.3, color="red") xs = X0.dot(P) ys = np.zeros_like(xs) plt.scatter(xs, ys) pretty_print(LatexExpr("Q =")) print(vecs) if print_ans: print("red point: center") print("red arrow: first principal component") print("orange points: projection of blue points onto the red arrow") print("red arrow = first column of Q") ``` ##### Exercise 1(a) 若藍點為給定的資料。 改變不同的 `seed`,說明紅點、紅箭頭、橘點的意思。 <!-- eng start --> Let the blue points be the dataset. Try different `seed` and explore the meaning of the red point, the red arrow, and the orange point. <!-- eng end --> ##### Exercise 1(b) 令 $X_0$ 的列向量為將藍點資料置中過後的資料點、 而 $C = \frac{1}{N-1}X_0\trans X_0$ 為其共變異數矩陣。 若 $C = QDQ\trans$ 為 $C$ 的譜分解,其中 $D$ 的對角線項由大到小排列。 說明紅箭頭與 $Q$ 的關係。 <!-- eng start --> Let $X_0$ be the matrix whose rows record the data from the blue points, centered at their mean. Let $C = \frac{1}{N-1}X_0\trans X_0$ be the covariance matrix. Suppose $C = QDQ\trans$ is the spectral decomposition of $C$ such that the diagonal entries of $D$ is arranged from the largest to the smallest. Explain the relation between the red arrow and $Q$. <!-- eng end --> :::info What do the experiments try to tell you? (open answer) ... ::: ## Exercises ##### Exercise 2 令 $X$ 是已置中的 $N\times d$ 資料矩陣、 而 $C = \frac{1}{N-1}X_0\trans X_0$ 為其共變異數矩陣。 令 $\bv$ 為一 $\mathbb{R}^d$ 中的單位向量。 說明 $\bu = X\bv$ 為將 $X$ 的所有樣本點投影在 $\bv$ 方向的值、 並說明 $\bu$ 的變異數為 $\bv\trans C\bv$。 <!-- eng start --> Let $X$ be a $N\times d$ data matrix whose rows are centered at their mean. Let $C = \frac{1}{N-1}X_0\trans X_0$ be the covariance matrix. Fix a unit vector $\bv$ in $\mathbb{R}^d$. Show that $\bu = X\bv$ records the length of data points in $X$ projected on $\bv$ and show that the variance of $\bu$ is $\bv\trans C\bv$. <!-- eng end --> ##### Exercise 3 執行以下程式碼。 <!-- eng start --> Run the code below. <!-- eng end --> ```python import numpy as np X = np.random.randn(3,4) u,s,vh = np.linalg.svd(X) vals,vecs = np.linalg.eigh(X.T.dot(X)) vals = vals[::-1] vecs = vecs[:,::-1] print("V =") print(vh.T) print("Q =") print(vecs) print("singular values:", s) print("eigenvalues:", vals) ``` ##### Exercise 3(a) 說明為什麼印出來的兩個矩陣會一樣。 (除了有的行會有正負號的差別。) <!-- eng start --> Explain why the two output matrices are the same (except that some of the columns are negated). <!-- eng end --> ##### Exercise 3(b) 說明印出來的奇異值和特徵值有什麼關係。 <!-- eng start --> Explain the relation between the singular values and the eigenvalues in the output. <!-- eng end --> ##### Exercise 3(c) 解釋 ```python vals = vals[::-1] vecs = vecs[:,::-1] ``` 的用處。 <!-- eng start --> Explain the meaning of ```python vals = vals[::-1] vecs = vecs[:,::-1] ``` <!-- eng end --> ##### Exercise 4 有時候我們只須要最大的幾個特徵值。 所以如果把所有的特徵值都算出來是不必要的浪費時間。 查找資源如何利用 SciPy 中的 `linalg.eigh` 找最大的幾個特徵值。 <!-- eng start --> Sometimes we only need the first few largest eigenvalues, and it is a waste of time to compute all eigenvalues. Search online and find out how to find the largest eigenvalues through `linalg.eigh` in SciPy. <!-- eng end --> ##### Exercise 5 給定 $k$ 時, $$ p = \frac{\sum_{i=1}^k \lambda_i}{\sum_{i=1}^d \lambda_i} $$ 稱作**變異數解釋率(explained variance ratio)**。 當解釋率夠高的時候,表示投影後的資料足以代表原資料的重要特徵。 觀察下圖,其橫軸為 $k$,縱軸為解釋率。 判斷 $k$ 應該要取多少,以及為什麼。 <!-- eng start --> For a given $k$, $$ p = \frac{\sum_{i=1}^k \lambda_i}{\sum_{i=1}^d \lambda_i} $$ is known as the **explained variance ratio** . When this rate is high enough, it means the projected data is representative enough for the original data. Observe the figure below, where the $x$-axis represents $k$ and the $y$-axis represents the explained variance ratio. Determine which $k$ is preferred and give your reasons. <!-- eng end --> ```python import numpy as np import matplotlib.pyplot as plt X = np.genfromtxt('hidden_text.csv', delimiter=',') print("shape of X =", X.shape) X = X - X.mean(axis=0) u,s,vh = np.linalg.svd(X) vals = s**2 plt.plot(np.arange(1,101), vals.cumsum() / vals.sum()) plt.gca().set_xlim(0,10) ``` ##### Exercise 6 找一個共變異數矩陣 `cov` 使得 `np.random.multivariate_normal` 產出來的資料大約是一個楕圓形,且: - 長軸指向 $45^\circ$ 角、短軸指向 $135^\circ$ 角; - 長軸是大約是短軸的 $2$ 倍。 <!-- eng start --> Find a covariance matrix `cov` such that the data generated by `np.random.multivariate_normal` is roughly an ellipse such that: - the major axis is on $45^\circ$, while the minor axis is on $135^\circ$; - the major axis is about twice the length of the minor axis. <!-- eng end --> ```python import numpy as np import matplotlib.pyplot as plt mu = np.array([0,0]) cov = np.array([ [1,0], [0,1] ]) X = np.random.multivariate_normal(mu, cov, (1000,)) plt.axis('equal') plt.scatter(*X.T) ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully