TypeError:'numpy.float64'对象无法解释为整数,并且转换为int失败

时间:2019-06-14 21:23:49

标签: python numpy scipy

我的代码-

import networkx as nx
import random
import numpy as np
import matplotlib.pyplot as plt
import math

def avg_deg(self,num_nodes):
        return self.number_of_edges() * 2 / num_nodes


def avg_degree(num_nodes,target_deg):

    G=nx.Graph()

    G.add_nodes_from(range(num_nodes))
    while avg_deg(G,num_nodes) < target_deg:
        n1, n2 = random.sample(G.nodes(), 2)
        G.add_edge(n1, n2, weight=1)

    return G    

a=np.arange(0,1, 0.001)
p_values=a.tolist()
p_values.pop(0)

graph=avg_degree(10000,4)

n_original=nx.number_of_nodes(graph)    

n_edges = graph.number_of_edges()
graph.remove_edges_from(random.sample(graph.edges(),k=int(0.9*n_edges)))
data=[len(c) for c in sorted(nx.connected_components(graph), key=len, reverse=True)]



xx= list(set(data))

yy= [data.count(x) for x in set(data)]

xx = [math.log(record) for record in xx]
yy =  [math.log(record) for record in yy]

plt.plot(xx,yy,'ro')
plt.xlabel('log(cluster_size)')
plt.ylabel('log(frequency)')
#plt.show()

plt.figure()

##################calculating exponent
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


def func(x, a, b, c):
    return a* np.exp(-b * x) + c

popt, pcov = curve_fit(func, xx, yy,maxfev=5000)


plt.plot(xx, func(xx, *popt), 'r-',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))    


plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

错误即将来临

  plt.plot(xx, func(xx, *popt), 'r-',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
  File "gaussian.py", line 82, in func
    return a * np.exp(-b * x) + c

我试图通过将所有a,b,c强制转换为int来解决此问题,但这也给了我一个错误-

D:\anaconda\lib\site-packages\scipy\optimize\minpack.py:785: OptimizeWarning: Covariance of the parameters could not be estimated
  category=OptimizeWarning)
Traceback (most recent call last):
  File "gaussian.py", line 87, in <module>
    plt.plot(xx, func(xx, *popt), 'r-',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
  File "D:\anaconda\lib\site-packages\matplotlib\pyplot.py", line 3261, in plot
    ret = ax.plot(*args, **kwargs)
  File "D:\anaconda\lib\site-packages\matplotlib\__init__.py", line 1717, in inner
    return func(ax, *args, **kwargs)
  File "D:\anaconda\lib\site-packages\matplotlib\axes\_axes.py", line 1372, in plot
    for line in self._get_lines(*args, **kwargs):
  File "D:\anaconda\lib\site-packages\matplotlib\axes\_base.py", line 404, in _grab_next_args
    for seg in self._plot_args(this, kwargs):
  File "D:\anaconda\lib\site-packages\matplotlib\axes\_base.py", line 384, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "D:\anaconda\lib\site-packages\matplotlib\axes\_base.py", line 243, in _xy_from_xy
    "have shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y must have same first dimension, but have shapes (11,) and (0,)
TypeError: 'numpy.float64' object cannot be interpreted as an integer

我的代码正在绘制图形中的log(频率)vs log(cluster_size)。现在我想找到指数曲线的a,b和c,因此我为此使用了scipy函数。基本上,我试图找到斜率〜pk ^ -y,并且试图找到y,因此我想使用scipy的曲线拟合方法来找到它。

1 个答案:

答案 0 :(得分:1)

您应该将功能func更改为

def func(x, a, b, c):
    return a* np.exp(-b * np.array(x)) + c

因为这里的参数应该是numpy array而不是python列表