简体   繁体   中英

Why does executing this function kill my kernel?

I have an old Jupyter notebook that I just fired up. It was written by somebody else and is a bit beyond my current ability (ie, can't just work around the problem myself).

It's a demonstration of k-means, and this function helps display the points.

# helper function that allows us to display data in 2 dimensions and highlights the clusters
def display_cluster(X,km=[],num_clusters=0):
    color = 'brgcmyk'
    alpha = 0.5
    s = 20
    if num_clusters == 0:
        plt.scatter(X[:,0],X[:,1],c = color[0],alpha = alpha,s = s)
    else:
        for i in range(num_clusters):
            plt.scatter(X[km.labels_==i,0],X[km.labels_==i,1],c = color[i],alpha = alpha,s=s)
            plt.scatter(km.cluster_centers_[i][0],km.cluster_centers_[i][1],c = color[i], marker = 'x', s = 100)

The next cell runs the function, and it always kills my kernel:

angle = np.linspace(0,2*np.pi,20, endpoint = False)
X = np.append([np.cos(angle)],[np.sin(angle)],0).transpose()
display_cluster(X)

If I comment out the first two lines, it will execute. When I call display_cluster(X) , my kernel dies.

How can I salvage this?

You're using a non-ipython kernel. The line that is causing the problem is:

# if num_clusters == 0:
#     plt.scatter(X[:,0],X[:,1],c = color[0],alpha = alpha,s = s)

This code block uses the plt.scatter() function to draw circles for each point in the dataset. If you are using IPython, the issue should be resolved by commenting out these two lines of code and running your notebook again. If you are using a non-IPython kernel, this line throws an error because we have not loaded the matplotlib library in our Python environment and so can't access its functions; but it would be loaded if we ran this cell in an IPython environment (notebook or console). Try that!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM