plt.scatter:IndexError:只有整数、切片(`:`)、省略号(`...`)、numpy.newaxis(`None`)和整数或布尔数组是有效索引

问题描述 投票:0回答:1

我想在我的数据集上绘制一个简单的散点图。

# Create polynomial features
poly = PolynomialFeatures(degree=2)
X_train_poly = poly.fit_transform(X_train_imputed)
X_test_poly = poly.transform(X_test_imputed)
# Train a Linear Regression model on the polynomial features
poly_reg = LinearRegression()
poly_reg.fit(X_train_poly, y_train)
# Make predictions
y_pred_poly = poly_reg.predict(X_test_poly)

#sketch the polynomial regression on the dataset
# Plot the polynomial regression
plt.figure(figsize=(10, 6))
plt.scatter(X_test_imputed['Level_of_Hemoglobin'], y_test, color='blue', label='Actual')  # line 173
plt.plot(X_test_imputed['Level_of_Hemoglobin'], y_pred_poly, color='red', linewidth=2, label='Predicted')
plt.xlabel('Level_of_Hemoglobin')
plt.ylabel('Blood Pressure')
plt.title('Polynomial Regression')
plt.legend()
plt.show()

但在第 173 行出现以下错误

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

我应该如何修复这个错误?到底是什么导致了这个错误?

python numpy
1个回答
0
投票

您遇到的错误,IndexError:只有整数,切片(:),省略号(...),numpy.newaxis(无)和整数或布尔数组是有效索引,通常在您尝试访问使用无效索引类型的数据结构元素。在这种情况下,问题似乎可能出在您访问 X_test_impulated DataFrame 中的列的方式上。发生该错误的原因可能是 X_test_impulated['Level_of_Hemoglobin'] 返回一个类似数组的对象,而不是 DataFrame 或 Series。要修复此错误,您需要确保 X_test_impulated['Level_of_Hemoglobin'] 返回一维数组或一系列。您可以通过使用 .values 访问列或使用 .squeeze() 将其显式转换为 Series 来完成此操作。 以下是修复错误的方法:

# Plot the scatter diagram
plt.figure(figsize=(10, 6))
plt.scatter(X_test_imputed['Level_of_Hemoglobin'].values, y_test, color='blue', label='Actual')
plt.plot(X_test_imputed['Level_of_Hemoglobin'].values, y_pred_poly, color='red', linewidth=2, label='Predicted')
plt.xlabel('Level_of_Hemoglobin')
plt.ylabel('Blood Pressure')
plt.title('Polynomial Regression')
plt.legend()
plt.show()

或者也许:

# Plot the scatter diagram
plt.figure(figsize=(10, 6))
plt.scatter(X_test_imputed['Level_of_Hemoglobin'].squeeze(), y_test, color='blue', label='Actual')
plt.plot(X_test_imputed['Level_of_Hemoglobin'].squeeze(), y_pred_poly, color='red', linewidth=2, label='Predicted')
plt.xlabel('Level_of_Hemoglobin')
plt.ylabel('Blood Pressure')
plt.title('Polynomial Regression')
plt.legend()
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.