溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Ignite中如何使用k-最近鄰分類算法

發(fā)布時間:2021-07-30 16:56:19 來源:億速云 閱讀:125 作者:Leah 欄目:云計(jì)算

Ignite中如何使用k-最近鄰分類算法,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

首先,要獲取原始數(shù)據(jù)并將其拆分成訓(xùn)練數(shù)據(jù)(60%)和測試數(shù)據(jù)(40%)。然后再次使用Scikit-learn來執(zhí)行這個任務(wù),下面修改一下前一篇文章中使用的代碼,如下:

from sklearn import datasets
import pandas as pd

# Load Iris dataset.
iris_dataset = datasets.load_iris()
x = iris_dataset.data
y = iris_dataset.target

# Split it into train and test subsets.
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=23)

# Save train set.
train_ds = pd.DataFrame(x_train, columns=iris_dataset.feature_names)
train_ds["TARGET"] = y_train
train_ds.to_csv("iris-train.csv", index=False, header=None)

# Save test set.
test_ds = pd.DataFrame(x_test, columns=iris_dataset.feature_names)
test_ds["TARGET"] = y_test
test_ds.to_csv("iris-test.csv", index=False, header=None)

當(dāng)訓(xùn)練和測試數(shù)據(jù)準(zhǔn)備好之后,就可以寫應(yīng)用了,本文的算法是:

  1. 讀取訓(xùn)練數(shù)據(jù)和測試數(shù)據(jù);

  2. 在Ignite中保存訓(xùn)練數(shù)據(jù)和測試數(shù)據(jù);

  3. 使用訓(xùn)練數(shù)據(jù)擬合k-NN模型;

  4. 將模型應(yīng)用于測試數(shù)據(jù);

  5. 確定模型的準(zhǔn)確性。

讀取訓(xùn)練數(shù)據(jù)和測試數(shù)據(jù)

需要讀取兩個有5列的CSV文件,一個是訓(xùn)練數(shù)據(jù),一個是測試數(shù)據(jù),5列分別為:

  1. 萼片長度(cm)

  2. 萼片寬度(cm)

  3. 花瓣長度(cm)

  4. 花瓣寬度(cm)

  5. 花的種類(0:Iris Setosa,1:Iris Versicolour,2:Iris Virginica)

通過下面的代碼,可以從CSV文件中讀取數(shù)據(jù):

private static void loadData(String fileName, IgniteCache<Integer, IrisObservation> cache)
        throws FileNotFoundException {

   Scanner scanner = new Scanner(new File(fileName));

   int cnt = 0;
   while (scanner.hasNextLine()) {
      String row = scanner.nextLine();
      String[] cells = row.split(",");
      double[] features = new double[cells.length - 1];

      for (int i = 0; i < cells.length - 1; i++)
         features[i] = Double.valueOf(cells[i]);
      double flowerClass = Double.valueOf(cells[cells.length - 1]);

      cache.put(cnt++, new IrisObservation(features, flowerClass));
   }
}

該代碼簡單地一行行的讀取數(shù)據(jù),然后對于每一行,使用CSV的分隔符拆分出字段,每個字段之后將轉(zhuǎn)換成double類型并且存入Ignite。

將訓(xùn)練數(shù)據(jù)和測試數(shù)據(jù)存入Ignite

前面的代碼將數(shù)據(jù)存入Ignite,要使用這個代碼,首先要創(chuàng)建Ignite存儲,如下:

IgniteCache<Integer, IrisObservation> trainData = getCache(ignite, "IRIS_TRAIN");
IgniteCache<Integer, IrisObservation> testData = getCache(ignite, "IRIS_TEST");
loadData("src/main/resources/iris-train.csv", trainData);
loadData("src/main/resources/iris-test.csv", testData);

getCache()的實(shí)現(xiàn)如下:

private static IgniteCache<Integer, IrisObservation> getCache(Ignite ignite, String cacheName) {

   CacheConfiguration<Integer, IrisObservation> cacheConfiguration = new CacheConfiguration<>();
   cacheConfiguration.setName(cacheName);
   cacheConfiguration.setAffinity(new RendezvousAffinityFunction(false, 10));

   IgniteCache<Integer, IrisObservation> cache = ignite.createCache(cacheConfiguration);

   return cache;
}

使用訓(xùn)練數(shù)據(jù)擬合k-NN分類模型

數(shù)據(jù)存儲之后,可以像下面這樣創(chuàng)建訓(xùn)練器:

KNNClassificationTrainer trainer = new KNNClassificationTrainer();

然后擬合訓(xùn)練數(shù)據(jù),如下:

KNNClassificationModel mdl = trainer.fit(
        ignite,
        trainData,
        (k, v) -> v.getFeatures(),     
// Feature extractor.

        (k, v) -> v.getFlowerClass())  
// Label extractor.

        .withK(3)
        .withDistanceMeasure(new EuclideanDistance())
        .withStrategy(KNNStrategy.WEIGHTED);

Ignite將數(shù)據(jù)保存為鍵-值(K-V)格式,因此上面的代碼使用了值部分,目標(biāo)值是Flower類,特征在其它列中。將k的值設(shè)為3,代表3種。對于距離測量,可以有幾個選擇,如歐幾里德、漢明或曼哈頓,在本例中使用歐幾里德。最后要指定是使用SIMPLE算法還是使用WEIGHTED k-NN算法,在本例中使用WEIGHTED。

將模型應(yīng)用于測試數(shù)據(jù)

下一步,就可以用訓(xùn)練好的分類模型測試測試數(shù)據(jù)了,可以這樣做:

int amountOfErrors = 0;
int totalAmount = 0;

try (QueryCursor<Cache.Entry<Integer, IrisObservation>> cursor = testData.query(new ScanQuery<>())) {
   for (Cache.Entry<Integer, IrisObservation> testEntry : cursor) {
      IrisObservation observation = testEntry.getValue();

      double groundTruth = observation.getFlowerClass();
      double prediction = mdl.apply(new DenseLocalOnHeapVector(observation.getFeatures()));

      totalAmount++;
      if (groundTruth != prediction)
         amountOfErrors++;

      System.out.printf(">>> | %.0f\t\t\t | %.0f\t\t\t|\n", prediction, groundTruth);
   }

   System.out.println(">>> -----------------------------");

   System.out.println("\n>>> Absolute amount of errors " + amountOfErrors);
   System.out.printf("\n>>> Accuracy %.2f\n", (1 - amountOfErrors / (double) totalAmount));
}

確定模型的準(zhǔn)確性

下面,就可以通過對測試數(shù)據(jù)中的真實(shí)分類和模型進(jìn)行的分類進(jìn)行對比,來確認(rèn)模型的真確性。

代碼運(yùn)行之后,總結(jié)如下:

>>> Absolute amount of errors 2
>>> Accuracy 0.97

因此,Ignite能夠?qū)?7%的測試數(shù)據(jù)正確地分類為3個不同的種類。

關(guān)于Ignite中如何使用k-最近鄰分類算法問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI