FASTKNN Procedure

Getting Started: FASTKNN Procedure

Note: Input data must be in a CAS table that is accessible in your CAS session. You must refer to this table by using a two-level name. The first level must be a CAS engine libref, and the second level must be the table name. For more information, see the sections Using CAS Sessions and CAS Engine Librefs and Loading a SAS Data Set onto a CAS Server in Chapter 2, Shared Concepts.

This example shows how to use the FASTKNN procedure to search for the k-nearest neighbors, from observations in a SAS data table to a set of query observations. In this case, the data are from the hmeq data set. This data set contains information about mortgage applicants. The example selects 4,000 applicants for the input data table, and 100 applicants for the query data table. The FASTKNN procedure returns the input applicants that are most similar to each of the query applicants. The analysis uses eleven variables: bad, loan, mortdue, value, yoj, derog, delinq, clage, ninq, clno, and debtinc. The remaining variables in the data table are not used.

You can load the hmeq data set into your CAS session by specifying your CAS engine libref in the first statement in the following DATA step. These statements assume that your CAS engine libref is named mylib, but you can substitute any appropriately defined CAS engine libref.

data mylib.hmeq;
    set sampsio.hmeq(obs=4000);
    id=_n_;
run;

data mylib.query;
    set sampsio.hmeq(firstobs=4001 obs=4100);
    id=_n_;
run;

The following statements run PROC FASTKNN and output the results to ODS tables:

proc fastknn
   data            = mylib.hmeq
   query           = mylib.query
   outdist         = mylib.dist_out
   K               = 4
   usetopkoutdist
   threshdist      = 10000;
   id                id;
   input             bad loan mortdue value yoj derog delinq clage ninq clno debtinc;
   output out      = mylib.knn_out;
run;

The K=4 option requests that the model return four neighbors; the USETOPKOUTDIST option requests that only the top k nearest distances be output to the OUTDIST= option table. the THRESHDIST=10000 option requests that the model exclude distances that are greater than 10,000; the ID statement specifies that the id variable be used as a record identifier; and the INPUT statement specifies that the variables bad, loan, mortdue, value, yoj, derog, delinq, clage, ninq, clno, and debtinc be used as inputs. The OUTPUT statement requests that the neighbors be written to the data table mylib.knn_out. The OUTDIST= option requests that the distances from the query observations to the input observations be written to the data table mylib.dist_out.

Last updated: August 06, 2026