วิธีแก้ไข: อินพุตมี nan ค่าอนันต์ หรือค่าสูงเกินไปสำหรับ dtype ('float64')


ข้อผิดพลาดทั่วไปที่คุณอาจพบเมื่อใช้ Python คือ:

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

ข้อผิดพลาดนี้มักเกิดขึ้นเมื่อคุณพยายามใช้ฟังก์ชันจากโมดูล scikit-learn แต่ DataFrame หรือเมทริกซ์ที่คุณใช้เป็นอินพุตมีค่า NaN หรือค่าอนันต์

ตัวอย่างต่อไปนี้แสดงวิธีการแก้ไขข้อผิดพลาดนี้ในทางปฏิบัติ

วิธีการทำซ้ำข้อผิดพลาด

สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:

 import pandas as pd
import numpy as np

#createDataFrame
df = pd. DataFrame ({' x1 ': [1, 2, 2, 4, 2, 1, 5, 4, 2, 4, 4],
                   ' x2 ': [1, 3, 3, 5, 2, 2, 1, np.inf, 0, 3, 4],
                   ' y ': [np.nan, 78, 85, 88, 72, 69, 94, 94, 88, 92, 90]})

#view DataFrame
print (df)

    x1 x2 y
0 1 1.0 NaN
1 2 3.0 78.0
2 2 3.0 85.0
3 4 5.0 88.0
4 2 2.0 72.0
5 1 2.0 69.0
6 5 1.0 94.0
7 4 lower 94.0
8 2 0.0 88.0
9 4 3.0 92.0
10 4 4.0 90.0

ตอนนี้ สมมติว่าเรากำลังพยายามปรับ โมเดลการถดถอยเชิงเส้นหลายตัวให้เหมาะสม โดยใช้ฟังก์ชัน scikit-learn :

 from sklearn. linear_model import LinearRegression

#initiate linear regression model
model = LinearRegression()

#define predictor and response variables
x, y = df[[' x1 ', ' x2 ']], df. y

#fit regression model
model. fit (x,y)

#print model intercept and coefficients
print (model. intercept_ , model. coef_ )

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

เราได้รับข้อผิดพลาดเนื่องจาก DataFrame ที่เราใช้มีทั้งค่าอนันต์และค่า NaN

วิธีการแก้ไขข้อผิดพลาด

วิธีแก้ไขข้อผิดพลาดนี้คือการลบแถวทั้งหมดออกจาก DataFrame ที่มีค่าอนันต์หรือค่า NaN ก่อน:

 #remove rows with any values that are not finite
df_new = df[np. isfinite (df). all ( 1 )]

#view updated DataFrame
print (df_new)

    x1 x2 y
1 2 3.0 78.0
2 2 3.0 85.0
3 4 5.0 88.0
4 2 2.0 72.0
5 1 2.0 69.0
6 5 1.0 94.0
8 2 0.0 88.0
9 4 3.0 92.0
10 4 4.0 90.0

ลบสองบรรทัดที่มีค่าอนันต์หรือ NaN ออกแล้ว

ตอนนี้เราสามารถดำเนินการให้เหมาะสมกับโมเดลการถดถอยเชิงเส้นของเราได้แล้ว:

 from sklearn. linear_model import LinearRegression

#initiate linear regression model
model = LinearRegression()

#define predictor and response variables
x, y = df_new[[' x1 ', ' x2 ']], df_new. y

#fit regression model
model. fit (x,y)

#print model intercept and coefficients
print (model. intercept_ , model. coef_ )

69.85144124168515 [5.72727273 -0.93791574]

โปรดทราบว่าเราไม่ได้รับข้อผิดพลาดใดๆ ในครั้งนี้ เนื่องจากเราได้ลบแถวที่มีค่าอนันต์หรือค่า NaN ออกจาก DataFrame ก่อน

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีแก้ไขข้อผิดพลาดทั่วไปอื่นๆ ใน Python:

วิธีแก้ไขใน Python: ไม่สามารถเรียกวัตถุ ‘numpy.ndarray’ ได้
วิธีแก้ไข: TypeError: ไม่สามารถเรียกวัตถุ ‘numpy.float64’ ได้
วิธีแก้ไข: ข้อผิดพลาดประเภท: สตริงที่คาดหวังหรือวัตถุไบต์

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *