Polynomial Fitting and Visualization with Python

Answered using ChatGPT 4o by ChatGPT4o

Question:

56.90 56.09 55.98 55.89 55.70 55.42 55.33 54.85 52.88 50.35 47.18 45.85 43.64 42.32 41.72 41.37 39.76 39.35 38.85 38.82 38.18 37.57 37.45 37.16 37.05 37.03 37.01 36.20 35.79 35.66 34.86 34.53 34.28 34.15 34.13 33.95 33.93 33.75 33.40 33.14 32.62 31.49 31.21 30.74 27.65 26.78 25.41 这些数据 帮我用4阶多项式拟合一下 给出公式计算结果 并画出图像 给出R^2

Answer:

好的,我可以帮助你进行四阶多项式拟合,并给出公式、计算结果、图像以及R²值。我们将使用Python中的numpymatplotlib库来完成这些任务。以下是具体步骤:

  1. 导入必要的库
  2. 准备数据
  3. 进行多项式拟合
  4. 计算R²值
  5. 绘制图像

以下是Python代码:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score

# 数据
data = [
    56.90, 56.09, 55.98, 55.89, 55.70, 55.42, 55.33, 54.85, 52.88, 50.35,
    47.18, 45.85, 43.64, 42.32, 41.72, 41.37, 39.76, 39.35, 38.85, 38.82,
    38.18, 37.57, 37.45, 37.16, 37.05, 37.03, 37.01, 36.20, 35.79, 35.66,
    34.86, 34.53, 34.28, 34.15, 34.13, 33.95, 33.93, 33.75, 33.40, 33.14,
    32.62, 31.49, 31.21, 30.74, 27.65, 26.78, 25.41
]

# 准备数据
x = np.arange(len(data))
y = np.array(data)

# 进行4阶多项式拟合
coefficients = np.polyfit(x, y, 4)
polynomial = np.poly1d(coefficients)

# 计算拟合值
y_fit = polynomial(x)

# 计算R²值
r2 = r2_score(y, y_fit)

# 打印多项式公式
print("拟合的4阶多项式公式为:")
print(polynomial)

# 打印R²值
print(f"R²值: {r2}")

# 绘制图像
plt.scatter(x, y, label='原始数据')
plt.plot(x, y_fit, color='red', label='4阶多项式拟合')
plt.xlabel('数据点')
plt.ylabel('值')
plt.title('4阶多项式拟合')
plt.legend()
plt.show()

运行上述代码后,你将得到以下结果:

  1. 拟合的4阶多项式公式
  2. R²值
  3. 图像

请确保你已经安装了numpymatplotlibscikit-learn库。如果没有安装,可以使用以下命令进行安装:

pip install numpy matplotlib scikit-learn

运行代码后,你将看到拟合的多项式公式和R²值,并且会显示一个包含原始数据和拟合曲线的图像。