python拟合曲线,用python拟合指数曲线

本文讨论了从Matlab代码转换为Python代码进行曲线拟合的问题,针对具体的数据集,提供了正确的Python实现方式,并解决了参数初始化及函数定义顺序等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am trying to convert some Matlab code I have for curve fitting my data into python code but am having trouble getting similar answers. The data is:

x = array([ 0. , 12.5 , 24.5 , 37.75, 54. , 70.25, 87.5 ,

108.5 , 129.5 , 150.5 , 171.5 , 193.75, 233.75, 273.75])

y = array([-8.79182857, -5.56347794, -5.45683824, -4.30737662, -1.4394612 ,

-1.58047016, -0.93225927, -0.6719836 , -0.45977157, -0.37622436,

-0.56115757, -0.3038559 , -0.26594558, -0.26496367])

The Matlab code is:

function [estimates, model] = curvefit(xdata, ydata)

% fits data to the curve y(x)=A-B*e(-lambda*x)

start_point = rand(1,3);

model =@efun;

options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);

estimates = fminsearch(model, start_point,options);

% expfun accepts curve parameters as inputs, and outputs sse,

% the sum of squares error for A -B* exp(-lambda * xdata) - ydata,

% and the FittedCurve.

function [sse,FittedCurve] = efun(v)

A=v(1);

B=v(2);

lambda=v(3);

FittedCurve =A - B*exp(-lambda*xdata);

ErrorVector=FittedCurve-ydata;

sse = sum(ErrorVector .^2);

end

end

err = Inf;

numattempts = 100;

for k=1:numattempts

[intermed,model]=curvefit(x, y));

[thiserr,thismodel]=model(intermed);

if thiserr

err = thiserr;

coeffs = intermed;

ymodel = thismodel;

end

and so far in Python I have:

import numpy as np

from pandas import Series, DataFrame

import pandas as pd

import matplotlib.pyplot as plt

from scipy import stats

from scipy.optimize import curve_fit

import pickle

def fitFunc(A, B, k, t):

return A - B*np.exp(-k*t)

init_vals = np.random.rand(1,3)

fitParams, fitCovariances = curve_fit(fitFunc, y, x], p0=init_vals)

I think I have to do something with running 100 attempts on the p0, but the curve only converges about 1/10 times and it converges to a straight line, way off from the value I get in Matlab. Also most questions regarding curve fitting that I have seen use Bnp.exp(-kt) + A, but the exponential formula I have above is the one I have to use for this data. Any thoughts? Thank you for your time!

解决方案

curve_fit(fitFunc, y, x], p0=init_vals) should be curve_fit(fitFunc, x,y, p0=init_vals) ie, x goes before y . fitFunc(A, B, k, t) should be fitFunc(t,A, B, k). The independent variable goes first. See the code below:

import numpy as np

import matplotlib.pyplot as plt

from scipy.optimize import curve_fit

x = np.array([ 0. , 12.5 , 24.5 , 37.75, 54. , 70.25, 87.5 ,

108.5 , 129.5 , 150.5 , 171.5 , 193.75, 233.75, 273.75])

y = np.array([-8.79182857, -5.56347794, -5.45683824, -4.30737662, -1.4394612 ,

-1.58047016, -0.93225927, -0.6719836 , -0.45977157, -0.37622436,

-0.56115757, -0.3038559 , -0.26594558, -0.26496367])

def fitFunc(t, A, B, k):

return A - B*np.exp(-k*t)

init_vals = np.random.rand(1,3)

fitParams, fitCovariances = curve_fit(fitFunc, x, y, p0=init_vals)

print fitParams

plt.plot(x,y)

plt.plot(x,fitFunc(x,*fitParams))

plt.show()

### Pandas 文件格式读写操作教程 #### 1. CSV文件的读取与保存 Pandas 提供了 `read_csv` 方法用于从 CSV 文件中加载数据到 DataFrame 中。同样,也可以使用 `to_csv` 将 DataFrame 数据保存为 CSV 文件。 以下是具体的代码示例: ```python import pandas as pd # 读取CSV文件 df = pd.read_csv('file.csv') # 加载本地CSV文件 [^1] # 保存DataFrame为CSV文件 df.to_csv('output.csv', index=False) # 不保存行索引 [^1] ``` --- #### 2. JSON文件的读取与保存 对于JSON格式的数据,Pandas 支持通过 `read_json` 和 `to_json` 进行读取和存储。无论是本地文件还是远程 URL 都支持。 具体实现如下所示: ```python # 读取本地JSON文件 df = pd.read_json('data.json') # 自动解析为DataFrame对象 [^3] # 从URL读取JSON数据 url = 'https://example.com/data.json' df_url = pd.read_json(url) # 直接从网络地址获取数据 # 保存DataFrame为JSON文件 df.to_json('output.json', orient='records') ``` --- #### 3. Excel文件的读取与保存 针对Excel文件操作Pandas 使用 `read_excel` 来读取 `.xls` 或 `.xlsx` 格式的文件,并提供 `to_excel` 方法导出数据至 Excel 表格。 注意:需要安装额外依赖库 `openpyxl` 或 `xlrd` 才能正常运行这些功能。 ```python # 安装必要模块 (如果尚未安装) !pip install openpyxl xlrd # 读取Excel文件 df_excel = pd.read_excel('file.xlsx', sheet_name='Sheet1') # 导出DataFrame为Excel文件 df.to_excel('output.xlsx', sheet_name='Sheet1', index=False) ``` --- #### 4. SQL数据库的交互 当涉及关系型数据库时,Pandas 可借助 SQLAlchemy 库连接各种类型的数据库(如 SQLite, MySQL)。它允许直接查询并将结果作为 DataFrame 返回;或者反过来把现有 DataFrame 插入到指定表中。 下面是基于SQLite的一个例子: ```python from sqlalchemy import create_engine # 创建引擎实例 engine = create_engine('sqlite:///database.db') # 查询SQL语句并返回DataFrame query = "SELECT name, salary, department FROM employees" sql_df = pd.read_sql(query, engine) # 计算各部门平均工资 avg_salary_by_dept = sql_df.groupby('department')['salary'].mean() # 将DataFrame存回SQL表 avg_salary_by_dept.to_sql(name='average_salaries_per_department', con=engine, if_exists='replace', index=True) ``` 上述片段说明了如何执行基本SQL命令以及后续数据分析流程[^4]。 --- #### 5. 多层次索引(MultiIndex)的应用场景 除了常规单维度索引外,在某些复杂情况下可能需要用到多级索引结构。这时可以依靠 MultiIndex 构建更加灵活的数据模型。 例如定义一个多层列名体系: ```python arrays = [['A','A','B','B'], ['foo','bar','foo','bar']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df_multi_indexed = pd.DataFrame([[0,1,2,3], [4,5,6,7]], columns=index) print(df_multi_indexed) ``` 这段脚本演示了怎样构建一个具有双重分类标签的表格布局[^2]。 --- ### 总结 综上所述,Pandas 是一种强大而易用的数据处理工具包,适用于多种常见文件类型之间的相互转换及其高级特性应用开发之中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值