古賀(コーガくん)
    • 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
    • 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 Versions and GitHub Sync Note Insights 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 4年目 この記事は[Kogakuin Advent Calendar 2018](https://adventar.org/calendars/2917) 1日目です. 初めましての方は初めまして お久しぶりの方はお久しぶり コーガくんこと古賀です Twitterは @takt0909 でツイートしていません. 完全に告知のみ扱いになっています. この記事を書いているのは2018.11.30で明日から12月ということに絶望しながら執筆してます. そして`b`のキーの反応が悪くなって途中から書くのが適当になりました. --- みなさん, コーガくん知ってますか? 私は詳しく知りません. 記憶が確かだと工学院大のマスコットで,ロケットの生まれ変わりでこのマスコットの着ぐるみの中が蒸し暑いくらいの記憶しかありません. 今日は`Python`というプログラミング言語を用いて簡単に`コーガくん`が写っているか写っていないかを分類するプログラムを書いていきたいと思います. >![](https://i.imgur.com/O8bCy0H.gif) >[コーガくん&クイーンちゃん](https://www.kogakuin.ac.jp/admissions/about/koga.html) **時間あったら後でしっかりと書きます** <s>もちろん! プログラミング初心者でもわかりやすいように説明する(予定だった)ので, ぜひお家でやってみてください.</s> ## はじめに 現在, 巷で`人工知能・AI`や`DeepLearning`という言葉を耳にしたことがある学生も多いと思います. Amazonの`この商品を買った人はこの商品も買っています`みたいに"購入した商品"と一緒に買われた商品を画面に表示して薦めてくる「レコメンドシステム」やスマートフォンやカメラ越しに人物を撮るときに顔を認識してくれる「認識システム」など私生活のありとあらゆるところで`いわゆるAIってやつ`が使われています. `人工知能・AI`というとターミネーターやドラえもんを想像する人も一部いるかもしれませんが, そういった類だけでなく, `人間がその全認知能力を必要としない程度の問題解決や推論を行うシステム`のことも指してたりします.(※) 今回扱うコーガくんが写っているか写ってないかを分類するプログラムも昔は難しい問題でした. コーガくんを犬に置き換えてみます. >犬を知らない人に対して犬とはなんですか? と説明するときに耳があって四足歩行で... と説明すると猫と勘違いするかもしれません. >つまり猫と勘違いしないように犬だとわかるよう**パターン**を説明しなければなりません.そしてそれをコンピュータに教えることは難しかったのです. 昔は 「パターン認識」という分野はコンピュータに次の画像は犬ですと教え, 次の画像は犬ではありません と教える. つまりコンピュータに犬の画像と犬でない画像を大量にインプットすることによって**自動**で「犬のパターンを取得」する技術がパターン認識なのです. 犬を言葉で説明できない人も写真に犬が写ってるか写ってないかわかるように,コンピュータも犬が写ってるか写ってないかわかるようになるのです! この「パターン認識」という技術も`人工知能・AI`の分野の一つと言われてたりします. では, 次にこの「パターン認識」技術を用いて実際にコーガくんが写ってるか写ってないか分類するプログラムを書いてみましょう. ## 準備 ### プログラムを動かす環境作り プログラムを書くときに一番めんどくさいのが,自分のパソコン上にプログラムできる環境を作ることです.例えば今回の場合だと`Python`をダウンロードしてきたりしないといけない. そんなのめんどくさい👿 そこで今回はGoogleが提供しているブラウザ上で動く環境`google colaboratory`を用いて「コーガくんを分類するプログラム」を書いてみたいと思います. まずは`google colaboratory`で検索してみましょう. ![](https://i.imgur.com/yl7dpqV.png) そして,[Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb?hl=ja)にアクセスします. この際にGoogleアカウントでログインしておくことを忘れずに! 次にファイルから`Python3の新しいノートブックをひらく`をクリックしてください. ![](https://i.imgur.com/6LeuufV.png) そして, こんな画面が出たらokです. ![](https://i.imgur.com/Vtzbm69.png) `google colaboratory`はweb上でpythonができるので非常に便利です. ぜひ色々使ってみて遊んでください. ### コーガくんの画像集め 次にコンピュータに教える`コーガくん`の画像を用意しないといけません. Googleで`コーガくん`と画像検索すると画像が出てくるので保存します.(※) ![](https://i.imgur.com/Hm1cjih.jpg) ※ 今回は画像を保存せずにURLをメモするだけにします. 本格的にやる場合には必要 ### プログラム (後で書く) 今回は巷で流行りの`DeepLearning`ではなく簡単に`SupportVectorMachine:SVM`を用いてコーガくんかどうか分類します. > 今回は画像をネットから取得してきて,64x64のサイズにリサイズします. その後, 主成分分析:PCAに入力するために画像を64x64x3次元の画像を1次元に変換します. > その後, PCAに入力して64x64x3次元の画像を2次元に変換する. > 最後に, SVMに2次元の情報とその答えを教えてコンピュータに学習させます. 実際に先ほど用意した`Google Colaboratory`に下記のコードをコピー&ペーストして▶︎を押して実行してみてください. (多分動きます) 動かすと次のように可視化できます. この赤い点がこーがくんの特徴量,緑の点がこーがくん意外の画像の特徴量です. そして,この線より上だとコーガくんと判定し下だとそれ以外と判定する境界線. この境界線をコンピュータに今回は学ばせました👏 ![](https://i.imgur.com/TmoKGak.png) ```python import numpy as np from sklearn import svm from PIL import Image import requests from io import BytesIO imgs = [] label = [] # 0:コーガくん, 1:コーガくんじゃない urls = [] #使う画像リスト(".jpg じゃないとダメ") koga_urls = [ # コーガくんの画像 #"https://www.kogakuin.ac.jp/admissions/about/cbr7au0000057gv4-img/71kogakun300.gif", "http://www.yurugp.jp/img/uploads/character/650/00001267.jpg", "https://pbs.twimg.com/media/BW1VNCmCAAMo6Xv.jpg", "https://pbs.twimg.com/media/CsHpZ58VIAAPM2b.jpg", "https://pbs.twimg.com/media/BUpWtmECAAAZbZ9.jpg", "https://cdn.mainichi.jp/vol1/2015/07/29/20150729org00m100012000p/51.jpg", "https://pbs.twimg.com/media/DYssADQVwAEuuUl.jpg", ] urls += koga_urls label = [0 for _ in range(0,len(koga_urls))] not_urls =[ # コーガくんじゃない画像 "http://www.yurugp.jp/img/uploads/character/650/00003918.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003774.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003772.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003771.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003770.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003769.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003768.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003767.jpg", "http://www.yurugp.jp/img/uploads/character/650/00003850.jpg" ] urls += not_urls label += [1 for _ in range(0,len(not_urls))] h, w = 64,64 data = np.zeros((len(label),h,w,3)) for idx,url in enumerate(urls): response = requests.get(url) img = Image.open(BytesIO(response.content)) img = img.resize((64,64)) img = np.asarray(img)/255. data[idx] = img train_x = data.reshape(len(data),64*64*3) train_y = np.array(label) # 次元圧縮 from sklearn.decomposition import PCA, RandomizedPCA pca=PCA(n_components=2) X = pca.fit_transform(train_x) # 分類アルゴリズム from sklearn.svm import LinearSVC clf = LinearSVC() clf.fit(X, label) # 可視化 plt.scatter(X[:,0],X[:,1],cmap=plt.cm.RdYlGn,c=[i for i in label]) x = np.linspace(-50,100,50) plt.plot(x, -(x*clf.coef_[0][0] + clf.intercept_[0])/clf.coef_[0][1], c='k',label="prediction border") plt.legend() plt.show() ``` ### 予測 実際に先ほど作成したプログラムに今までコンピュータに勉強させなかった新しい画像を渡して`コーガくん`の写っている画像がどうか判断してもらいます. ```python # 予測したい画像のURLを添付 # sample(コーガくん) #url = "http://www.kogakuin-koyukai.jp/kogakuin/wp-content/uploads/2018/10/03834b-150x150.jpg" #url = "https://pbs.twimg.com/media/DYssADQVwAEuuUl.jpg" # sample(Not コーガくん) url = "http://www.yurugp.jp/img/uploads/character/650/00003750.jpg" # 前処理 response = requests.get(url) img = Image.open(BytesIO(response.content)) img = img.resize((64,64)) img = np.asarray(img)/255. # 次元圧縮 test = pca.transform(img.reshape(1,64*64*3)) # 予測結果: koga→コーガくん etc→その他 result = clf.predict(test) print(label2name[result[0]]) ``` ![](https://i.imgur.com/CYl9t46.png) ![](https://i.imgur.com/3hH5ynn.png) 一応, コーガくんかそれ以外かを分類できるようになりましたー ※一部画像入力するとエラー吐くらしいので直します.. すまそ `ValueError: could not broadcast input array from shape (64,64,4) into shape (64,64,3)` ## おわりに どうでしたか? 今年が4年目になります. 不幸なことにまだ枠が空いているので書いていただける方大募集です.. てか助けてください. プログラミングというと小難しいイメージがあると思いますが, 文部科学省によると2020年以降に小学校からプログラミング教育必修化を盛り込んだ学習指導要領改定案が発表されていたりと難しいと言ってられなくなってきたりします. そして英語も小学校から始めてるのにできない人が多いのにプログラミングなんて大丈夫なんでしょうか? 嫌いになったりしないでしょうか? なんて考えてしまいます. 私は英語できません. そんなことより. ![](https://i.imgur.com/jVBBVAG.jpg) 明日は,工学院大卒の社会人2年目のOBの記事です.楽しみですね♡

    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