【问题标题】:Improve Polynomial Curve Fitting using numpy/Scipy in Python Help Needed在 Python 中使用 numpy/Scipy 改进多项式曲线拟合 需要帮助
【发布时间】:2015-06-20 14:21:03
【问题描述】:

我有两个 NumPy 数组时间并且没有获取请求。我需要使用一个函数来拟合这些数据,以便我可以做出未来的预测。 这些数据是从存储日志文件详细信息的 cassandra 表中提取的。所以基本上时间格式是纪元时间,这里的训练变量是get_counts。

from cassandra.cluster import Cluster    
import numpy as np    
import matplotlib.pyplot as plt   
from cassandra.query import panda_factory

session = Cluster(contact_points=['127.0.0.1'], port=9042).connect(keyspace='ASIA_KS')         
session.row_factory = panda_factory    
df = session.execute("SELECT epoch_time, get_counts FROM ASIA_TRAFFIC")    
.sort(columns=['epoch_time','get_counts'], ascending=[1,0])    
time = np.array([x[1] for x in enumerate(df['epoch_time'])])    
get = np.array([x[1] for x in enumerate(df['get_counts'])])    
plt.title('Trend')    
plt.plot(time, byte,'o')    
plt.show()

数据如下: 大约有1000对数据

time -> [1391193000 1391193060 1391193120 ..., 1391279280 1391279340 1391279400 1391279460]

get -> [577 380 430 ...,250 275 365  15]

绘图图像(full size here):

有人可以帮我提供一个函数,以便我可以正确地适应数据吗?我是 python 新手。

编辑 *

fit = np.polyfit(time, get, 3)
yp = np.poly1d(fit)
plt.plot(time, yp(time), 'r--', time, get, 'b.')
plt.xlabel('Time')    
plt.ylabel('Number of Get requests')    
plt.title('Trend')    
plt.xlim([time[0]-10000, time[-1]+10000])
plt.ylim(0, 2000)
plt.show()
print yp(time[1400])

拟合曲线如下所示:
https://drive.google.com/file/d/0B-r3Ym7u_hsKUTF1OFVqRWpEN2M/view?usp=sharing

但是在曲线的后半部分,y 的值变为 (-ve),这是错误的。曲线必须将其斜率更改回介于两者之间的 (+ve)。 谁能建议我如何去做。 帮助将不胜感激。

【问题讨论】:

  • 有点话题,但是你为什么在 create timebyte 的列表推导中使用 enumerate
  • @wwii 如果我不使用枚举函数,df['epoch_time'] 和 df['byte_transfer'] 充当标量变量,它不能像在代码中那样索引。但是,在代码中不需要使用枚举。我可以简单地使用 time = np.array(df['epoch_time']) 它会完成我的工作。
  • 看起来这个数据有一些非常清晰的周期性成分,我也会在其中包含一个 sin() 成分来捕捉周期性。

标签: python numpy matplotlib curve-fitting non-linear-regression


【解决方案1】:

你可以试试:

time = np.array([x[1] for x in enumerate(df['epoch_time'])])    
byte = np.array([x[1] for x in enumerate(df['byte_transfer'])]) 

fit = np.polyfit(time, byte, n) # step up n value here, 
                                # where n is the degree of the polynomial 
yp = np.poly1d(fit)
print yp                        # displays function in cx^n +- cx^n-1...c format

plt.plot(x, yp(x), '-')

plt.xlabel('Time')    
plt.ylabel('Bytes Transfered')    
plt.title('Trend')    
plt.plot(time, byte,'o')    
plt.show()

我也是 Numpy 和曲线拟合的新手,但我一直在尝试这样做。

【讨论】:

  • 感谢您的帮助。使用您的代码后,曲线看起来像这样:drive.google.com/file/d/0B-r3Ym7u_hsKRTNjNXJ1b3Z4b2c/… n 的值但是不会给曲线带来任何差异。我从 3 开始,到 20 结束,找不到任何改变,这是我能做的最好的吗?
  • 很高兴它帮助了一些人。希望我能提供更多帮助,但这是我在不亲自处理数据的情况下能做的最好的事情
猜你喜欢
  • 2013-10-10
  • 2012-04-25
  • 2015-09-14
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
相关资源
最近更新 更多