简体   繁体   中英

KNN ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

here is my code, it's supposed to be a simple regression algorithm. The data set has about 500 samples, each of them have 12 factors. I received this error though:

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

Code:

dataset = pd.read_csv('/Users/chrisrivas/Documents/Andrew     Haines/Datasets/GRD.csv', header=None, sep=',')

#coverts dataset into 2d array of values and seperates target column
#[1st to: last rows, and 1st to: 12th columns ]
samples = dataset.loc[:, 1:12].values
targets = dataset[13].values

print(samples)
print(targets)

#training and testing of dataset
X_train, X_test, y_train, y_test = cross_validation.train_test_split(
samples, targets, test_size=0.35, random_state=0)

knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train, y_train)

y_pred = knn.predict(X_test)

#calculates accuracy of algorithm    
print("Test set score: {:.2f}%".format(np.mean(y_pred == y_test)*100))

#opens new data for algorithm to make classification predictions 
dataset2 = pd.read_csv('/Users/chrisrivas/Documents/Datasets/GoldRushDataset-41.csv', header=None, sep=',').values

#continues to loop for each sample and their classification prediction
for sample in dataset2:
    prediction = knn.predict([sample])
    print("Prediction: {}".format(prediction))
    print('    ')    

#other format for predictions: all at a time in array
prediction = knn.predict(dataset2)
print("Prediction: {}".format(prediction))

Have you checked for NaNs (not a number) in your dataset2? eg. with dataset2.isnull().values.any() ?

Another thing that might be the cause of your error: You need to treat the samples the same way as you treat your training data:

knn.predict(dataset2.loc[:, 1:12].values)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM