【问题标题】:KNN ValueError: Input contains NaN, infinity or a value too large for dtype('float64')KNN ValueError:输入包含 NaN、无穷大或对于 dtype('float64') 来说太大的值
【发布时间】:2019-02-17 18:49:44
【问题描述】:

这是我的代码,它应该是一个简单的回归算法。该数据集有大约 500 个样本,每个样本有 12 个因子。我收到了这个错误:

ValueError: 输入包含 NaN、无穷大或一个太大的值 dtype('float64').

代码:

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))

【问题讨论】:

  • 您是否检查过 dataset2 中的 NaN(不是数字)?例如。 dataset2.isnull().values.any()?
  • 没有,但我刚试了一下,我的输出没有任何新信息...
  • 输出是什么? dataset2 有 NaN 吗?
  • 还有一件事:你为什么不像对待训练数据那样对待样本呢? IE。 knn.predict(dataset2.loc[:, 1:12].values)
  • 谢谢,我想我现在可以使用它了,但是我注意到每次运行代码时,我都会在测试中得到相同的分数。我认为每次运行代码时它都会对随机样本进行训练和测试,但事实并非如此。任何帮助将不胜感激。

标签: python nan


【解决方案1】:

您是否检查过数据集中的 NaN(不是数字)2?例如。 dataset2.isnull().values.any()?

另一件事可能是您的错误的原因:您需要像对待训练数据一样对待样本:

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

【讨论】:

    猜你喜欢
    • 2017-11-23
    • 2016-07-31
    • 2020-08-16
    • 2020-05-25
    • 2020-10-23
    • 2020-04-10
    • 1970-01-01
    • 2023-01-11
    • 2019-08-25
    相关资源
    最近更新 更多