Posted on

使PostgreSQL支持向量相似度搜尋

安裝相關套件pgvector

套件Github頁面

https://github.com/pgvector/pgvector

pgvector可做到Postgres 的開源向量相似度搜索,將向量與其他數據一起存儲。

支援:

  • 精確和近似最近鄰搜索
  • 單精度(single-precision)、半精度(half-precision)、二進位(binary)和稀疏向量(sparse vectors)
  • L2 距離(L2 distance)、內積(inner product)、餘弦距離(cosine distance)、L1 距離(L1 distance)、漢明距離(Hamming distance)和 Jaccard 距離(Jaccard distance)
  • 具有 Postgres 用戶端的任何語言
  • 支持 ACID 合規性、時間點恢復、JOIN 和 Postgres 的所有其他強大功能

Linux安裝

cd /tmp
git clone --branch v0.7.2 https://github.com/pgvector/pgvector.git
cd pgvector
make
make install # may need sudo

Windows安裝

首先安裝VisualStudioSetup,此為下載連結: https://visualstudio.microsoft.com/downloads/

接著至少勾選這些套件

執行C的編譯環境

call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"

使用nmake編譯檔案

set "PGROOT=C:\Program Files\PostgreSQL\16"
cd %TEMP%
git clone --branch v0.7.2 https://github.com/pgvector/pgvector.git
cd pgvector
nmake /F Makefile.win
nmake /F Makefile.win install

建立可儲存的向量的資料欄位

pgvector的資料格式為vector(1536),後面的(1536)代表長度,此為OpenAI的embedding長度

以下為一個建立表格的SQL範例

CREATE TABLE IF NOT EXISTS public.test_example
(
    id character varying(255) COLLATE pg_catalog."default" NOT NULL,
    embeddings vector(1536),
    CONSTRAINT test_example_pkey PRIMARY KEY (id)
)

在Object Explorer按右鍵選擇,Query Tool可開啟SQL輸入介面,要瀏覽現有資料庫表格列表可至Schemas->Tables瀏覽

新增資料至資料表

以下為一個範例

import psycopg2
df = pd.read_csv('./data.csv')
def convert_embedding(embedding_str):
    return list(map(float, embedding_str.split(',')))

df["embeddings"] = df["embeddings"].apply(literal_eval)

row = df.iloc[0]
sql = """
    INSERT INTO fare_info (
        id, embeddings 
    ) VALUES (
        %s, %s
    )
"""

conn = psycopg2.connect(dbname="myDB", user="myUser", password="xxxxxx")
cursor = conn.cursor()
cursor.execute(sql, (row['id'],row['embeddings']))
conn.commit()

並行搜索的擴展套件AnalyticDB 

AnalyticDB 是阿里巴巴雲推出的云原生數據倉庫,它基於 PostgreSQL 開發,並進行了一些增強,以提高性能和可擴展性。AnalyticDB 也支持 pgvector,但它具有以下一些增強功能:

  • 分布式向量搜索:AnalyticDB 可以將向量數據分佈在多個節點上,並並行處理向量搜索查詢。這使得它能夠比基於單機 PostgreSQL 的 pgvector 更快地處理大型向量數據集。
  • 向量壓縮:AnalyticDB 支持向量壓縮,這可以減少向量數據的存儲空間。
  • 向量索引:AnalyticDB 支持向量索引,這可以提高向量搜索查詢的性能。

總而言之,AnalyticDB 中的 pgvector 與 PostgreSQL 中的 pgvector 相同,但它具有以下一些增強功能:

  • 分布式向量搜索
  • 向量壓縮
  • 向量索引

這些增強功能使 AnalyticDB 更加適合處理大型向量數據集。

Posted on

如何設定與操作PostgreSQL

了解安裝的PostgreSQL的相關資訊

像我是使用CentOS,因此我可以用下面的指令來得知現在系統中PostgreSQL的運行狀況

sudo systemctl status postgresql-13
● postgresql-13.service - PostgreSQL 13 database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql-13.service; enabled; vend>
   Active: active (running) since Sat 2024-06-08 22:48:41 UTC; 2 weeks 1 days a>
     Docs: https://www.postgresql.org/docs/13/static/
 Main PID: 3264201 (postmaster)
    Tasks: 8 (limit: 23678)
   Memory: 27.6M
   CGroup: /system.slice/postgresql-13.service
           ├─3264201 /usr/pgsql-13/bin/postmaster -D /var/lib/pgsql/13/data/
           ├─3264202 postgres: logger
           ├─3264204 postgres: checkpointer
           ├─3264205 postgres: background writer
           ├─3264206 postgres: walwriter
           ├─3264207 postgres: autovacuum launcher
           ├─3264208 postgres: stats collector
           └─3264209 postgres: logical replication launcher

Warning: Journal has been rotated since unit was started. Log output is incompl>

從回覆的資料可以看出,設定檔的資料會在/var/lib/pgsql/13/data/,接著就搜尋裡面的設定檔*.conf

[root@aia16 13]# find /var/lib/pgsql/13 -name *.conf
/var/lib/pgsql/13/data/postgresql.conf
/var/lib/pgsql/13/data/postgresql.auto.conf
/var/lib/pgsql/13/data/pg_hba.conf
/var/lib/pgsql/13/data/pg_ident.conf

允許非本機的連線

PostgreSQL 默認配置只允許本地連接(即 localhost127.0.0.1),這是出於安全考量。要允許遠程連接,需要修改 PostgreSQL 的配置文件並設置適當的防火牆規則。以下是允許遠程連接的步驟:

1. 修改 postgresql.conf 文件,打開 postgresql.conf 文件,找到 listen_addresses 配置項,將其設置為 ' * ' 以允許所有地址連接,或者指定特定的 IP 地址。例如:

listen_addresses = '*'

修改 pg_hba.conf 文件,添加允許遠程連接的規則。

host    all             all             0.0.0.0/0               md5

如果你只想允許特定的 IP 地址範圍,例如 192.168.1.0/24,可以這樣設置:

host    all             all             192.168.1.0/24          md5

接著重啟PostgreSQL

sudo systemctl restart postgresql

Posted on

Tesseract – Google開源的光學文字辨識系統

關於Tesseract

Tesseract 是一個開源的光學字符識別(OCR)引擎,能夠將圖像中的文本轉換為可編輯的文本。它由 Google 維護和開發,支持多種語言和字符集。

GitHub位置: https://github.com/tesseract-ocr/tesseract

Tesseract 4 添加了一個新的基於神經網路 (LSTM) 的 OCR 引擎,該引擎專注於行識別,但仍然支援 Tesseract 3 的傳統 Tesseract OCR 引擎,該引擎通過識別字元模式來工作。使用舊版 OCR 引擎模式 (–oem 0) 啟用與 Tesseract 3 的相容性。它還需要支援舊引擎的 traineddata 檔,例如來自 tessdata 儲存庫的檔。

Tesseract 支援 unicode (UTF-8),可以「開箱即用」地識別 100 多種語言。支援多種圖像格式,包括 PNG、JPEG 和 TIFF。支援各種輸出格式:純文本、hOCR (HTML)、PDF、不可見文本 PDF、TSV、ALTO 和 PAGE。

主要功能和特點

  1. 多語言支持: Tesseract 支持超過 100 種語言,包括繁體中文。
  2. 高準確度: Tesseract 在文本識別方面具有較高的準確度,特別是經過適當的預處理後。
  3. 易於集成: Tesseract 可以與多種編程語言和工具集成,例如 Python、C++、Java 等,方便開發者在不同的應用場景中使用。
  4. 開源和免費: Tesseract 是開源軟件,可以自由使用和修改。

安裝 Tesseract

需要安裝兩個部分:引擎本身和語言的 traineddata。超過 130 種語言和超過 35 種腳本的軟體包也可以直接從 Linux 發行版獲得。語言 traineddata 包稱為“tesseract-ocr-langcode”和“tesseract-ocr-script-scriptcode”,其中 langcode 是三個字母的語言代碼, scriptcode 是四個字母的腳本代碼。

安裝教學: https://tesseract-ocr.github.io/tessdoc/InstallationOpenSuse.html

以 root 身份運行以下命令:(CentOS7)

yum-config-manager --add-repo https://download.opensuse.org/repositories/home:/Alexander_Pozdnyakov/CentOS_7/
sudo rpm --import https://build.opensuse.org/projects/home:Alexander_Pozdnyakov/public_key
yum update
yum install tesseract 
yum install tesseract-langpack-deu

使用方式

  • 從發佈頁面下載AppImage
  • 開啟終端應用程式
  • 流覽到 AppImage 的位置
  • 使 AppImage 可執行:$ chmod a+x tesseract*.AppImage
  • 執行它:./tesseract*.AppImage -l eng page.tif page.txt

安裝 pytesseract

pytesseract 是一個 Python 包裝器,用於調用 Tesseract OCR 引擎。

pip install pytesseract
pip install pillow

使用 Tesseract 進行 OCR

from PIL import Image
import pytesseract

# 設定 tesseract 執行檔的路徑
pytesseract.pytesseract.tesseract_cmd = r'/usr/local/bin/tesseract'  # 替換為你的 tesseract 安裝路徑

# 打開圖像文件
image = Image.open('example.png')

# 使用 Tesseract 進行 OCR
text = pytesseract.image_to_string(image, lang='chi_tra')  # 使用繁體中文語言包
print(text)
Posted on

安裝Postgresql和PgAdmin過程記錄

Postgresql安裝教學

安裝的指令如下

sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-$(rpm -E %rhel)-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum -qy module disable postgresql
sudo yum install -y postgresql13-server postgresql13
sudo /usr/pgsql-13/bin/postgresql-13-setup initdb
sudo systemctl enable postgresql-13
sudo systemctl start postgresql-13
sudo -i -u postgres
psql

接著建立資料庫

CREATE USER myuser WITH PASSWORD 'mypassword';
CREATE DATABASE mydb;
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;

退出命令行

\q
exit

安裝PgAdmin

以下為安裝的指令建議

$ sudo mkdir /var/lib/pgadmin
$ sudo mkdir /var/log/pgadmin
$ sudo chown $USER /var/lib/pgadmin
$ sudo chown $USER /var/log/pgadmin
$ python3 -m venv pgadmin4
$ source pgadmin4/bin/activate
(pgadmin4) $ pip install pgadmin4
...
(pgadmin4) $ pgadmin4
NOTE: Configuring authentication for SERVER mode.

Enter the email address and password to use for the initial pgAdmin user account:

Email address: user@domain.com
Password: 
Retype password:
Starting pgAdmin 4. Please navigate to http://127.0.0.1:5050 in your browser.
 * Serving Flask app "pgadmin" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off

強烈建議使用 Python 虛擬環境,不然因為牽涉到的library眾多,很容易會有函式庫之間的彼此衝突

安裝及啟動pgAdmin的方法

以下為安裝方式

$ sudo mkdir /var/lib/pgadmin
$ sudo mkdir /var/log/pgadmin
$ sudo chown $USER /var/lib/pgadmin
$ sudo chown $USER /var/log/pgadmin
$ python3 -m venv pgadmin4
$ source pgadmin4/bin/activate
(pgadmin4) $ pip install pgadmin4
...
(pgadmin4) $ pgadmin4
NOTE: Configuring authentication for SERVER mode.

Enter the email address and password to use for the initial pgAdmin user account:

Email address: user@domain.com
Password: 
Retype password:
Starting pgAdmin 4. Please navigate to http://127.0.0.1:5050 in your browser.
 * Serving Flask app "pgadmin" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off

啟動則只需要

$ source pgadmin4/bin/activate
(pgadmin4) $ pgadmin4

問題1 : 無法啟動pgAdmin

錯誤訊息

No module named '_sqlite3'

解決方法

首先先安裝所需要的套件

sudo apt update
sudo apt install libsqlite3-dev

接著要找到PYTHON的位置並且重新編譯

把下面的/path/to/python/source換成你的PYTHON的根目錄

cd /path/to/python/source
sudo ./configure --enable-optimizations
sudo make
sudo make altinstall

然後就可以正常啟動囉!

問題2:只能從127.0.0.1連線

使用下面指令找到套件位置

pip show pgadmin4 | grep Location

修改config

找到下面這行並將127.0.0.1改成0.0.0.0

DEFAULT_SERVER = '0.0.0.0'

問題3: 開啟防火牆5050端口

sudo systemctl start firewalld
sudo systemctl enable firewalld
sudo firewall-cmd --zone=public --add-port=5050/tcp --permanent
sudo firewall-cmd --reload
sudo firewall-cmd --zone=public --list-ports

最後一行是用以檢查是否已打開,如果 5050/tcp 在列表中,則表示已成功打開。

接著把SELINUX的端口打開

sudo semanage port -a -t http_port_t -p tcp 5050

就可以成功連線啦!

Posted on

YOLOv8使用範例

建模的範例

先用下面指令安裝好所需的套件

pip install ultralytics

然後在Roloflow下載要訓練的素材集,選擇YOLOv8

把裡面的資料(含data.yaml)解壓縮在同層資料夾下,如圖

接著直接執行下面的程式,yolov8會自動下載所需要的yolov8.yamlyolov8n.pt

import multiprocessing
import os
from ultralytics import YOLO
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'

def my_function():
    model = YOLO('yolov8.yaml').load("yolov8n.pt")
    # Train the model
    model.train(data='./data.yaml', epochs=300, imgsz=640)
    model.val(data="./data.yaml")

if __name__ == '__main__':
    multiprocessing.freeze_support()  # Optional, if you're freezing the script
    my_function()

這時候會出現錯誤如下,因為資料集放在哪邊也是剛剛才自動下載的,所以我們要打開一下這個設定檔案,設定一下我們的資料集的正確位置(datasets_dir)

看到這些訊息就代表成功的開始建模型囉!

模型使用範例

重點是在這行

model = YOLO('best.pt')

這行在載入我們建好的模型

results = model(image, show=False, verbose=False)

model這個預測方法有很多可控制的參數,例如要不要直接秀出圖片、要不要存圖片等等

YOLOv8非常貼心的是在於說,其吐出的物件如result,只要print這個物件,就會有非常詳細的結構和屬性意義教學,在開發上非常的方便

import VideoStream
import cv2
import numpy as np
from ultralytics import YOLO


videostream = VideoStream.VideoStream((1280, 720), 30, 0).start()
cam_quit = 0
model = YOLO('best.pt')
# 繪製邊框和標籤
def detect(image):
    results = model(image, show=False, verbose=False)
    # Show the results
    result = list(results)[0]
    for i in range(len(result.boxes)):
        r = result[i].boxes
        cls = int(r.cls[0].item())
        xywh = r.xywh[0].tolist()
        x_center, y_center, width, height = [int(x) for x in xywh[:4]]
        if width < 100 and height < 100:
            x1 = int(x_center - (width / 2))
            y1 = int(y_center - (height / 2))
            x2 = x1 + width
            y2 = y1 + height
            cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 3)
            cv2.putText(image, result.names[cls], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 1, cv2.LINE_AA) 

while cam_quit == 0:
    imageSource = videostream.read()
    imageSource = cv2.resize(imageSource, (960, 540))
    detect(imageSource)
    cv2.imshow("image", imageSource)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        cam_quit = 1

videostream.stop()
cv2.destroyAllWindows()

Posted on

pyav介紹

甚麼是pyav

PyAV是FFmpeg的Python封裝,旨在提供底層庫的全部功能和控制,同時盡可能管理繁瑣的細節。PyAV用於直接和精確地訪問媒體,包括容器、流、封包、編解碼器和幀。它還提供了一些數據轉換功能,並幫助您在其他程序之間傳送數據(例如Numpy和Pillow)。

然而,由於媒體處理非常複雜,PyAV無法完全抽像或為您做出所有最佳決策。 如果FFmpeg命令可以滿足您的需求,那麼PyAV可能會成為阻礙。 但在必要時,PyAV是一項關鍵工具。安裝PyAV可能有一些複雜的依賴關係,但現在可以在PyPI上找到針對Linux、Mac和Windows的二進位安裝套件。

官方網站: https://pyav.org/docs/stable/

GitHub位置: https://github.com/PyAV-Org/PyAV

建議使用場景

pyAVffmpeg 都是用來處理影音的工具,但它們的使用場景和方法有所不同。以下是對兩者的比較,以及根據不同情境的建議:

  1. 使用介面
    • pyAV:是一個 Python 函式庫,允許開發者使用 Python 語言來操作影音資料。
    • ffmpeg:是一個命令行工具,通常被用於進行批量處理或在沒有 Python 環境的系統上執行。
  2. 易用性和彈性
    • pyAV:由於是 Python 函式庫,使用者可以利用 Python 語言的所有特性來進行更複雜的操作,比如條件式處理、迴圈等。這使得對於需要更細緻操作的場景,例如資料分析、特定範圍的編輯等,pyAV 更有優勢。
    • ffmpeg:對於直接和簡單的影音轉換、剪裁、合併等操作,ffmpeg 的命令行界面非常適用。它能夠快速完成大部分的基本任務。
  3. 整合和擴展性
    • 如果你正在開發一個 Python 應用程序,並且希望直接在程式中處理影音,那麼 pyAV 可能是更好的選擇。
    • 如果只是簡單的一次性任務,或者需要在不同的平台或系統上腳本化影音處理,那麼 ffmpeg 可能更為適合。

結論

  • 如果你是 Python 開發者,且希望在程式中進行複雜的影音操作,那麼 pyAV 是個不錯的選擇。
  • 如果你只需要執行基本的影音轉換、剪裁或合併等操作,且希望能在多種平台上快速執行,那麼直接使用 ffmpeg 命令行工具可能更加適合。

安裝方法

使用以下方式安裝(如果下面的指令失敗的話,請參考此頁面安裝: https://pyav.org/docs/stable/overview/installation.html)

pip install av

後來我是使用下面這方法安裝成功的(windows)

pip install av --no-binary av
git clone https://github.com/PyAV-Org/PyAV.git
cd PyAV-main
python setup.py build --ffmpeg-dir=C:\ffmpeg

簡單的拉取RTMP源流的範例

以下的範例會拉取rtmp://127.0.0.1/live/testStream並使用OpenCV的函數顯示影像在視窗裡

import av
import cv2
import numpy as np
import os
import signal

def exit(*args,**kwargs):
    os.kill( os.getpid(), 9 )
signal.signal(signal.SIGINT,exit)

print('opening video...')
video = av.open('rtmp://127.0.0.1/live/testStream', 'r')

print('start streaming')
try:
    for packet in video.demux():
        for frame in packet.decode():
            if packet.stream.type == 'video':
                img = frame.to_ndarray(format='bgr24')
                cv2.imshow("Test", img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
except KeyboardInterrupt:
    print(KeyboardInterrupt)
    pass
cv2.destroyAllWindows()
Posted on

conda無法安裝套件,缺少OpenSSL解決方案

錯誤訊息

Collecting package metadata (current_repodata.json): failed CondaSSLError: OpenSSL appears to be unavailable on this machine. OpenSSL is required to download and install packages. Exception: HTTPSConnectionPool(host=’conda.anaconda.org’, port=443): Max retries exceeded with url: /conda-forge/win-64/current_repodata.json (Caused by SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”))

使用pip install/conda install跳出的錯誤

解決方法

在anaconda3>Library>bin尋找這兩個檔案

  • libcrypto-1_1-x64.dll
  • libssl-1_1-x64.dll

然後複製到anaconda3>DLLs.

相關討論串

https://github.com/conda/conda/issues/11982

Posted on

PyCharm – 好用的python開發環境

官方網站

https://www.jetbrains.com/pycharm/

為什麼選擇PYCHARM

  • 所有 PYTHON 工具集中在一處
  • 提高生產力: 在 PyCharm 處理例程時節省時間。專注於更大的事情並採用以鍵盤為中心的方法來充分利用 PyCharm 的許多生產力功能。
  • 獲得智能幫助: PyCharm 了解您的代碼的一切。依靠它實現智能代碼完成、實時錯誤檢查和快速修復、輕鬆的項目導航等等。
  • 提升代碼質量: 編寫整潔且可維護的代碼,同時 IDE 通過 PEP8 檢查、測試協助、智能重構和大量檢查幫助您控制質量。
  • 只需您所需要的: PyCharm 由程序員設計,為程序員而設計,旨在提供高效 Python 開發所需的所有工具。

免費的社區版本和付費的專業版本

功能比較圖

專業版的優惠方案

若為在學學生,可以獲得免費帳號
https://www.jetbrains.com/community/education/#students
若以畢業,但是電子信箱仍然可以用,則也可以用學校的信箱申請學生版本使用。

另外,對於一些電腦學院或者是初期創業者也都有提供優惠,個人使用者也有優惠(更多資訊: https://www.jetbrains.com/pycharm/buy/#discounts)

下載連結

請點此下載: https://www.jetbrains.com/pycharm/download/#section=windows

點進去右邊為免費版本,左邊為付費版本,但是可以免費使用30天

Posted on 1 Comment

在python裡面使用GPU 3 – 開發GPU程式

GPU運算與CPU運算的不同

下面是GPU 和CPU 之間的一些主要區別:

  • 運算單元:GPU 通常具有數百甚至數千個運算單元,而CPU 通常只有幾十個運算單元。
  • 並行運算能力:由於GPU 具有更多的運算單元,它能夠同時處理更多的數據,因此在並行運算方面具有優勢。
  • 計算能力:在單位時間內,GPU 的計算能力通常要高於CPU。
  • 功耗:由於GPU 具有更多的運算單元,它的功耗通常比CPU 高。
  • 用途:GPU 專門用於圖形處理,通常用於遊戲、視頻播放和圖形設計等任務。而CPU 則是計算機的中央處理器,負責處理各種計算任務。

指定使用的GPU

在程式中使用 GPU 時,需要在執行模型訓練或推理時將運算放在 GPU 上。您可以使用 TensorFlow 的 tf.device 函數指定運算的裝置。例如,您可以將運算放在第一個可用的 GPU 上:

with tf.device('/gpu:0'):
  # 在這裡放置您的運算
  pass

此外,可能需要注意 GPU 記憶體使用量。當您的模型變得越大,可能需要更多的 GPU 記憶體。可以使用 TensorFlow 的 tf.config.experimental.set_virtual_device_configuration 函數設定虛擬裝置配置以指定可用 GPU 的記憶體數量。

開發GPU程式

對開發人員而言,最大的不同就是,GPU運算會需要將資料在入GPU裡面,而當資料在GPU裡面時,我們並沒有辦法直接像當資料在CPU裡面時一樣,可以很方便的使用print來查看裡面的內容。
也因此,針對支援GPU的陣列運算庫,我們可以發現,通常在做陣列運算時,會呼叫相關的方法去做運算,如:

另外在載入資料時,也要注意使用既有可使用GPU載入資料的函數載入資料至正確的GPU上面(例如 tf.data),避免資料頻繁地在GPU和CPU之內轉換

避免資料頻繁地在GPU和CPU之內轉換

要避免資料頻繁地在 GPU 和 CPU 之間轉換,可以考慮以下幾點:

  • 將資料放在 GPU 上:使用 tf.device 函數指定資料所在的裝置。
  • 將運算和資料放在同一個 GPU 上:這樣可以避免資料在 GPU 和 CPU 之間頻繁轉換。
  • 使用高效的數據讀取方式:使用 TensorFlow 的數據讀取功能(例如 tf.data)可以更有效地讀取和轉換數據,並減少磁盤 I/O 的負擔。

更高效的使用GPU

  • 將運算放在 GPU 上:使用 tf.device 函數指定運算的裝置。
  • 設定虛擬裝置配置:使用 tf.config.experimental.set_virtual_device_configuration 函數指定可用 GPU 的記憶體數量。
  • 使用數據平行:將模型的數據分成多個 batch 並同時在多個 GPU 上訓練,可以提升訓練速度。您可以使用 TensorFlow 的 tf.distribute.Strategy API 來實現數據平行。
  • 調整 batch size:適當調整 batch size 可以平衡訓練速度和 GPU 記憶體使用量。

在tensorflow裡面自動最佳化使用GPU

TensorFlow 可以自動偵測可用的 GPU,並將運算自動分配到 GPU 上。要讓 TensorFlow 自動最佳化使用 GPU,您需要:

安裝 NVIDIA 驅動程式和 CUDA Toolkit。
安裝 GPU 版本的 TensorFlow。
在安裝 NVIDIA 驅動程式和 CUDA Toolkit 時,請確保安裝適用於您的 GPU 的版本。您可以在 NVIDIA 網站上查看可用驅動程式的列表。

安裝 GPU 版本的 TensorFlow 時,您需要使用 tensorflow-gpu 套件。您可以使用 pip 安裝:

pip install tensorflow-gpu

安裝完成後,TensorFlow 就會自動偵測可用的 GPU,並將運算自動分配到 GPU 上。您不需要在程式中手動指定運算的裝置。

注意:如果您的系統中沒有可用的 GPU,TensorFlow 會使用 CPU。

Posted on 1 Comment

在python裡面使用GPU 2 – 安裝正確的套件

前置作業

使用 GPU 來加速 Python 程式的運算需要:

  • 電腦必須要有適合的 GPU 及相關驅動程式。
  • 必須安裝支援 GPU 的 Python 程式庫,例如 TensorFlow、PyTorch 或 CuPy。
  • 在使用這些程式庫時將運算指定給 GPU 執行

安裝Tensorflow GPU版本的函式庫

在上面幾步驟都安裝好之後,要確認自己所使用的函式庫是支援GPU的,一般來說,所有的函式庫都會分為【支持GPU版本】或者【針對CPU版本】。
所以要先確定自己所下載的函式庫是支持GPU的。如果你的環境之前已經安裝過CPU版本的該函式庫,建議新增另一個虛擬環境,讓新專案的函式庫能夠完全與CPU版本的程式分開
這邊是使用pip安裝tensorflow套件的流程:https://www.tensorflow.org/install/pip?hl=zh-tw
在最下方有一個列表https://www.tensorflow.org/install/pip?hl=zh-tw#package-location

若是想要直接確定要下載的版本,可從上面的列表下載.whl檔案,然後用以下指令套用

pip install tensorflow-apu-0.0.1-cp36-cp36m-linux_x86_64.whl

檢查有沒有Tensorflow 可用的GPU

可使用下面的程式來檢查

import tensorflow as tf
print("TensorFlow version:", tf.__version__)

print("Is there a GPU available: "),
print(tf.config.list_physical_devices("GPU"))

print("Is the Tensor on GPU #0:  "),
print(x.device.endswith('GPU:0'))

要注意的是,即使你的GPU和驅動程式都正確,但若是安裝到錯誤的函式庫版本(如CPU版本的tensorflow)
這邊仍然會顯示沒有可以使用的GPU

因此,要確認所安裝的函式庫版本是否正確

檢查並設定使用GPU

要在 TensorFlow 中使用 GPU,你需要先檢查有沒有可用的 GPU,並設定 TensorFlow 使用 GPU:

import tensorflow as tf

# 檢查有沒有可用的 GPU
print(tf.config.list_physical_devices('GPU'))

# 設定 TensorFlow 使用 GPU
tf.config.set_visible_devices(tf.config.list_physical_devices('GPU')[0], 'GPU')

要在 PyTorch 中使用 GPU,你可以使用 torch.cuda.is_available() 來檢查有沒有可用的 GPU,並使用 .to(‘cuda’) 將張量放到 GPU 上運算:

import torch

# 檢查有沒有可用的 GPU
print(torch.cuda.is_available())

# 將張量放到 GPU 上運算
x = torch.ones((2, 2), device='cuda')
print(x)

在 CuPy 中使用 GPU 也類似,你可以使用 cp.cuda.Device().id 來檢查有沒有可用的 GPU,並使用 .to_gpu() 將陣列放到 GPU 上運算:

import cupy as cp

# 檢查有沒有可用的 GPU
print(cp.cuda.Device().id)

# 將陣列放到 GPU 上運算
x = cp.ones((2, 2))
x = x.to_gpu()
print(x)