训练KNN分类器后如何预测特定图像(来自数据集或来自外部数据集)

时间:2019-05-10 21:18:16

标签: python image-processing classification prediction

我有一个简单的KNN分类问题,下面的代码输出是训练分类器并将数据集分为“训练”和“测试”后得到的分类器的准确性。

我希望我的系统是:

  • 首先,使用数据集训练分类器;
  • 从URL上传图像;
  • 根据数据集对其进行分类。

例如,输出应为“ class 1”。我相信这很简单,但是我对python还是很陌生。

from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=5)

dataset = pd.read_csv(fdes)

X = dataset.iloc[:,:20].values
y = dataset['target'].values


from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
neigh.fit(X_train, y_train)

# Predicting the Test set results
y_pred = neigh.predict(X_test)

y_compare = np.vstack((y_test,y_pred)).T

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
#finding accuracy from the confusion matrix.
a = cm.shape
corrPred = 0
falsePred = 0

    #prining results
for row in range(a[0]):
    for c in range(a[1]):
        if row == c:
            corrPred +=cm[row,c]
        else:
            falsePred += cm[row,c]
kernelRbfAccuracy = corrPred/(cm.sum())
print ('Accuracy of  knn : ', corrPred/(cm.sum()))

1 个答案:

答案 0 :(得分:1)

完成所有这些步骤后,您可以继续:

from io import BytesIO
import numpy as np
import requests
from PIL import Image

response = requests.get(url)
img = Image.open(BytesIO(response.content))
img = np.array(img).reshape(1, -1)
output_class = neigh.predict(img)[0]
print(output_class)