curve fitting by a sum of gaussian with scipy

天涯浪子 提交于 2019-12-11 04:05:42

问题


I'm doing bioinformatics and we map small RNA on mRNA. We have the mapping coordinate of a protein on each mRNA and we calculate the relative distance between the place where the protein bound the mRNA and the site that is bound by a small RNA.

I obtain the following dataset :

dist    eff
-69 3
-68 2
-67 1
-66 1
-60 1
-59 1
-58 1
-57 2
-56 1
-55 1
-54 1
-52 1
-50 2
-48 3
-47 1
-46 3
-45 1
-43 1
0   1
1   2
2   12
3   18
4   18
5   13
6   9
7   7
8   5
9   3
10  1
13  2
14  3
15  2
16  2
17  2
18  2
19  2
20  2
21  3
22  1
24  1
25  1
26  1
28  2
31  1
38  1
40  2

When i plot the data, i have 3 pics : 1 at around 3 -4 another one around 20 and a last one around -50.

I try cubic spline interpolation, but it does'nt work very well for my data.

My idea was to do curve fitting with a sum of gaussians. For example in my case, estimate 3 gaussian curve at point 5,20 and -50.

How can i do so ?

I looked at scipy.optimize.curve_fit(), but how can i fit the curve at precise intervalle ? How can i add the curve to have one single curve ?


回答1:


import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
import scipy.optimize

data = np.array([-69,3, -68, 2, -67, 1, -66, 1, -60, 1, -59, 1,
                 -58, 1, -57, 2, -56, 1, -55, 1, -54, 1, -52, 1,
                 -50, 2, -48, 3, -47, 1, -46, 3, -45, 1, -43, 1,
                 0, 1, 1, 2, 2, 12, 3, 18, 4, 18, 5, 13, 6, 9,
                 7, 7, 8, 5, 9, 3, 10, 1, 13, 2, 14, 3, 15, 2,
                 16, 2, 17, 2, 18, 2, 19, 2, 20, 2, 21, 3, 22, 1,
                 24, 1, 25, 1, 26, 1, 28, 2, 31, 1, 38, 1, 40, 2])
x, y = data.reshape(-1, 2).T

def tri_norm(x, *args):
    m1, m2, m3, s1, s2, s3, k1, k2, k3 = args
    ret = k1*scipy.stats.norm.pdf(x, loc=m1 ,scale=s1)
    ret += k2*scipy.stats.norm.pdf(x, loc=m2 ,scale=s2)
    ret += k3*scipy.stats.norm.pdf(x, loc=m3 ,scale=s3)
    return ret


params = [-50, 3, 20, 1, 1, 1, 1, 1, 1]

fitted_params,_ = scipy.optimize.curve_fit(tri_norm,x, y, p0=params)

plt.plot(x, y, 'o')
xx = np.linspace(np.min(x), np.max(x), 1000)
plt.plot(xx, tri_norm(xx, *fitted_params))
plt.show()

>>> fitted_params
array([ -60.46845528,    3.801281  ,   13.66342073,   28.26485602,
          1.63256981,   10.31905367,  110.51392765,   69.11867159,
         63.2545624 ])

So you can see your idea of the three peaked function doesn't agree too much with your real data.



来源:https://stackoverflow.com/questions/16082171/curve-fitting-by-a-sum-of-gaussian-with-scipy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!