Python中NotFittedError()异常的常见错误和修复方法
发布时间:2023-12-18 15:45:28
1. NotFittedError()异常常见错误:
- 当尝试使用尚未拟合(fit)的模型进行预测或者转换时,会抛出NotFittedError()异常。
- 当尝试调用尚未拟合(fit)的模型的属性和方法时,也会抛出NotFittedError()异常。
2. 修复方法:
- 在使用模型进行预测或者转换之前,确保模型已经拟合。
- 在调用模型的属性和方法之前,确保模型已经拟合。
3. 使用例子:
from sklearn.linear_model import LinearRegression
from sklearn.exceptions import NotFittedError
# 创建一个线性回归模型
model = LinearRegression()
# 尝试使用尚未拟合的模型进行预测
try:
X = [[1, 1], [1, 2], [2, 2], [2, 3]]
model.predict(X)
except NotFittedError as e:
print(e) # 输出:"This LinearRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator."
# 拟合模型
y = [2, 3, 4, 5]
model.fit(X, y)
# 再次尝试预测
y_pred = model.predict(X)
print(y_pred) # 输出:[1. 3. 3.5 4.5]
# 尝试调用尚未拟合模型的属性
try:
coef = model.coef_
except NotFittedError as e:
print(e) # 输出:"This LinearRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator."
# 获取模型的系数
model.fit(X, y)
coef = model.coef_
print(coef) # 输出:[0.5 0.5]
在例子中,我们首先创建了一个线性回归模型,并尝试使用尚未拟合的模型进行预测和调用属性,都抛出了NotFittedError异常。然后我们调用了fit方法拟合了模型,再次进行预测和调用属性,都成功地返回了结果。
