TWTom
    • 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
    • Make a copy
    • 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 Make a copy 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
    --- type: slide --- # Python基礎教學 ### 蔡昕翰 --- # Python簡介 1. 簡單易學 2. 高生產力 3. 跨多領域 4. 高可讀性 5. 動態Typing 6. 直譯式 7. 跨平台 --- # 安裝conda ### 1. Miniconda 沒有太多預裝軟體,最小化安裝 ### 2. Anaconda 預裝很多東西,對科學計算可以輕易使用 --- # 什麼是conda 1. free & open source 2. 管理不同環境 3. 解決環境衝突 --- # 安裝Miniconda ### 1. 從官網 https://docs.conda.io/projects/miniconda/en/latest/ ### 2. 我的server (使用學校網路可以較快) --- # conda 指令介紹 ## 檢查python、conda版本 ```bash $ conda -V conda 23.1.0 $ python -V Python 3.10.6 ``` --- ## 查看conda環境 ```bash conda env list ``` --- ## conda建立新環境 ```bash conda create -n <env_name> python=<python_ver> ``` 例如 ```bash conda create -n py39 python=3.9 ``` --- ## 進入/退出conda虛擬環境 ```bash conda activate <env> # 進入環境 conda deactivate <env> # 退出環境 ``` 例如 ```bash $ python -V 'python' 不是內部或外部命令、可執行的程式或批次檔。 $ conda activate py39 (py39) $ python -V Python 3.9.13 (py39) $ conda deactivate $ python -V 'python' 不是內部或外部命令、可執行的程式或批次檔。 ``` --- ## python 互動模式 在終端機直接打python ```bash $ conda activate py39 (py39) $ python Python 3.9.13 (tags/v3.9.13:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print("hello, world") hello, world >>> exit() $ ``` --- ## python script - 產品用程式(production project)通常會寫成script - 需有IDE (vscode, PyCharm, vim, nano, 記事本...) ---- <br> <div style="text-align: left"> 例: </div> 1. 建立檔案 test.py 2. 在test.py內輸入: ```python= print("hello, world") ``` 3. 在終端機輸入: ```bash $ python test.py hello, world ``` --- ## jupyter notebook - 教學用、特定用途、科學及統計運算 - 嫌醜可用其他外殼包(vscode notebook mode, dataspell, ...) - 可遠端連線操作 --- ## 安裝jupyter ```bash (py39) $ pip install jupyter ``` 查看版本: ```bash (py39) $ jupyter --version Selected Jupyter core packages... IPython : 7.31.1 ipykernel : 6.19.2 ipywidgets : 7.6.5 jupyter_client : 7.3.4 jupyter_core : 5.1.1 jupyter_server : 1.23.4 jupyterlab : 3.5.2 nbclient : 0.5.13 nbconvert : 6.4.4 nbformat : 5.7.0 notebook : 6.5.2 qtconsole : 5.2.2 traitlets : 5.7.1 ``` --- ## 啟動jupyter notebook ```bash (py39) $ jupyter notebook ``` --- ## 在jupyter內建立新筆記本 ![](https://hackmd.io/_uploads/rkbqYq_Rn.png) --- ![](https://hackmd.io/_uploads/rJENsqdA2.png) --- 自己改筆記本名字 --- # Python基礎語法 easyeee~ --- 所有東西都是物件 --- 變數、賦值 ```python= message = "Hello World" print(message) ``` --- 條件判斷 ```python= x = 5 if x > 0 : print("x是正數") ``` --- 函數定義 ```python= def sayHello(name): print("Hello " + name) sayHello("John") ``` --- for循環結構 ```python= for i in range(5): print(i) list1 = [1,2,3] for item in list1: print(item) ``` --- while 循環 ```python= i = 10 while i > 0: print(i) ``` ```python= i = 10 f = False while not f: if i == 0: f = True print(i) ``` --- ## python的型別 python的變數可以隨意改變型別 ```python= number = 1 # int print(number) number = "asdf" # str print(number) ``` 會印出 ```python= 1 asdf ``` --- 檢查型別 ```python= random_thing = 1.3 print(type(random_thing)) ``` 會印出 ``` <class 'float'> ``` --- 數據結構 ```python= myList = [1, 2, 3] # 列表 list myTuple = (1, 2, 3) # 元組 tuple myDict = {"name": "John", "age": 25} # 字典 dict mySet = {1, 2, 3} # 集合 set ``` --- 取值 ```python= myList = [1, 2, 3] # 列表 list myTuple = (1, 2, 3) # 元組 tuple myDict = {"name": "John", "age": 25} # 字典 dict mySet = {1, 2, 3} # 集合 set print(myList[0]) print(myTuple[1]) print(myDict["name"]) print(mySet[2]) ``` --- ## 轉換型別 只有同種的可以互換 ``` ex: list <--> tuple str <--> list int <--> float ``` ```python= a = "abcdefg" print(list(a)) print(tuple( list(a) )) b = 1 c = 2 print(float(b) + float(c)) ``` --- ## 笨電腦 ```python= print(0.1 + 0.2) ``` --- # 數據分析 --- ## 什麼是numpy? - Python的開源數值計算擴展程式庫 - 提供高效能的多維陣列與矩陣運算、數學函數等功能 - 機器學習和數據科學的基礎套件 --- ## numpy安裝 ```bash pip install numpy ``` *使用我的伺服器* ```bash pip install numpy --extra-index-url http://<my_ip> --trusted-host <my_ip> ``` --- ## numpy使用 首先需要匯入numpy模組,通常用np代稱 ```python import numpy as np ``` --- ## 建立ndarray ndarray為numpy的多維陣列物件 ```python array = np.array([1, 2, 3]) matrix = np.array([[1, 2], [3, 4]]) ``` --- ## ndarray屬性 - ndarray.shape: 陣列維度 - ndarray.dtype: 陣列中的元素類型 ```python array.shape # (3,) matrix.shape # (2, 2) array.dtype # int64 ``` --- ## 新增維度 可以使用np.newaxis或None來新增維度 ```python= array_2d = array[np.newaxis, :] # [[1,2,3]] array_3d = array[:, np.newaxis, np.newaxis] # [[[1]],[[2]],[[3]]] ``` --- ## 陣列運算 向量化運算,適用於整個陣列 ```python matrix + 2 matrix * matrix # 元素對應相乘 ``` --- ## 常用函數 - `np.linspace`: 創建線段陣列 - `np.mean`: 計算均值 - `np.sum`: 總和 - `np.min/max`: 最小值和最大值 等等 --- # pandas基本用法 --- ## 什麼是pandas pandas是基於numpy的Python數據分析庫,提供: - 高效的數據結構(Series、DataFrame) - 數據讀取/寫入工具 - 數據清理與處理方法 - 合併/連接數據集功能 --- ## 安裝pandas ```bash pip install pandas ``` *使用我的伺服器* ```bash pip install pandas --extra-index-url http://<my_ip> --trusted-host <my_ip> ``` --- ## 使用pandas 引入數據庫,通常會使用pd代稱 ```python import pandas as pd ``` --- ## Series 一維數據,可設置索引 ```python s = pd.Series([1,2,3], index=['a','b','c']) ``` --- ## DataFrame 二維數據,類似表格/excel ```python data = {'Name': ['John', 'Mary'], 'Age': [25, 27]} df = pd.DataFrame(data) ``` --- ## 讀取csv ```python df = pd.read_csv('data.csv') ``` --- ## 查看資料 - `df.head()`/`df.tail()` - `df.shape` - `df.dtypes` - `df.index`/`df.columns` - `df.values` - `df.describe()` 統計訊息 --- ## 數據選取 - `df[col]`: column - `df.loc[index]`: 行 - `df.iloc[index]`: 位置 --- ## 數據清理 - 刪除列: `del df[col]` - 填補NaN: `df.fillna()` - 去除重復的: `df.drop_duplicates()` --- # OpenCV-Python (cv2) 基本用法 --- ## 安裝OpenCV 使用pip裝: ``` pip install opencv-python ``` *使用我的伺服器* ```bash pip install opencv-python --extra-index-url http://<my_ip> --trusted-host <my_ip> ``` --- ## 什麼是OpenCV? OpenCV是開源的電腦視覺庫,提供許多影像處理和電腦視覺相關的功能。 最新版本是4.x,Python繫結是cv2。 ```python import cv2 ``` --- 為何是cv2不是cv? --- ## 讀取圖像 ```python img = cv2.imread('image.jpg') ``` 支援讀取JPG、PNG、TIFF等格式。 --- ## 顯示圖像 ```python cv2.imshow('Image', img) cv2.waitKey(0) # 按任意鍵繼續 ``` --- ## 寫入圖像 ```python cv2.imwrite('output.jpg', img) ``` --- ## 圖像資訊 - `img.shape` - 形狀 - `img.size` - 大小 - `img.dtype` - 數據類型 --- ## 圖像處理 - 色彩空間轉換:`cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)` - 縮放:`cv2.resize(img, (width, height))` - 裁剪:`img[y1:y2, x1:x2]` - 模糊:`cv2.blur(img, (5, 5))` --- # Matplotlib基本用法 --- 安裝: ```bash pip install matplotlib ``` *使用我的伺服器* ```bash pip install matplotlib --extra-index-url http://<my_ip> --trusted-host <my_ip> ``` --- ## 什麼是Matplotlib Matplotlib是Python的2D繪圖庫,廣泛用於繪製論文的數據圖表。 ```python import matplotlib.pyplot as plt ``` --- ## 繪製圖表 ### 線圖 ```python x = [1, 2, 3, 4] y = [2, 4, 6, 8] plt.plot(x, y) ``` ### 柱狀圖 ```python x = ['A', 'B', 'C', 'D'] y = [10, 30, 40, 20] plt.bar(x, y) ``` --- ## imshow顯示圖片 ```python img = cv2.imread('image.jpg') plt.imshow(img) ``` --- ## 圖標題、軸標籤 ```python plt.title('Title') plt.xlabel('X Label') plt.ylabel('Y Label') ``` --- ## 圖片範圍、刻度 ```python plt.xlim(0, 5) plt.ylim(0, 10) plt.xticks([0, 1, 2, 3, 4, 5]) plt.yticks([0, 2, 4, 6, 8, 10]) ``` --- ## 圖例、顯示 ```python plt.legend(['A', 'B']) plt.show() ``` --- ## 感謝 祝AI之路順遂

    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