将拟合的曲线保存为xlsx文件,并保存参数

将拟合的曲线保存为xlsx文件,并保存参数

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import math

def plot_data(x, y):
    # 绘制原始数据的散点图
    plt.scatter(x, y)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.show()
    
    
def fit_func(x, a, b,c,d,e):
#     return a*x +b
    return a*x**4 +b*x**3+c*x**2+d*x+e

def fit_data(x, y):

    # 使用Levenberg-Marquardt算法拟合
    popt, _ = curve_fit(fit_func, x, y)

    # 绘制原始数据和拟合曲线
    plt.scatter(x, y, label='Original Data')
    plt.plot(x, fit_func(x, *popt), label='Nonlinear Fit')

    # 计算预测误差
    y_pred = fit_func(x, *popt)
    residuals = y_pred - y
    mae = np.mean(np.abs(residuals))
    
    print("Mean Absolute Error (MAE):", mae)
    
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.show()

    # 提取拟合参数
#     a, b= popt
    a, b,c,d,e= popt

    # 打印拟合参数
    print("a =", a)
    print("b =", b)
    print("c =", c)
    print("d =", d)
    print("e =", e)

    # 创建包含原始数据、预测数据和残差的 DataFrame
    result_df = pd.DataFrame({
        'x': x,
        'y': y,
        '预测值': y_pred,
        '绝对误差': residuals
#         'mae':mae
    })

    # 将 DataFrame 保存到 Excel 文件
    result_df.to_excel('path.xlsx', index=False)
    # 创建包含拟合参数的 DataFrame
    parameters = pd.DataFrame({'Parameters': ['a', 'b', 'c', 'd','e'], 'Values': popt})

#     # 如果需要,也可以保存拟合参数到 Excel
#     with pd.ExcelWriter('path.xlsx') as writer:
#         pd.DataFrame({'Parameters': ['a', 'b', 'c', 'd'], 'Values': popt}).to_excel(writer, index=False)
    with pd.ExcelWriter('path.xlsx') as writer:
        result_df.to_excel(writer, sheet_name='Data and Predictions', index=False)
        parameters.to_excel(writer, sheet_name='Fitting Parameters', index=False)

# 读取CSV文件
data = pd.read_csv('data.csv')

# 提取前两行数据
row1 = data.iloc[147]
# 选择特定的列
i= 39
columns = [f'Amp_{0.5*n+1}' for n in range(0, i)]

print(row1)
# print(row2[columns])
# 绘制散点图

    
x = range(i) 
x = np.array(x)  # 将x转换为数组类型
y = row1[columns]
#y = row2[columns]

plot_data(x,y)
fit_data(x, y)
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值