要在Ubuntu上使用OpenCV2進行機器學習,您需要首先安裝必要的軟件包和庫
sudo apt update
sudo apt install python3 python3-pip
pip3 install virtualenv
virtualenv venv
source venv/bin/activate
pip install opencv-python
pip install numpy matplotlib scikit-learn
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix
# 加載數據集
data = np.loadtxt('digits.csv', delimiter=',')
X = data[:, :-1]
y = data[:, -1].astype(int)
# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 數據預處理
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 創建KNN分類器
knn = KNeighborsClassifier(n_neighbors=3)
# 訓練模型
knn.fit(X_train, y_train)
# 預測
y_pred = knn.predict(X_test)
# 評估模型
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
python your_script.py
這只是一個簡單的示例,實際上您可以使用更復雜的算法和技術來進行機器學習。請確保根據您的需求調整代碼。