如何为Python实现此import语句?

时间:2018-08-14 17:07:03

标签: python import

我在网上找到了一个用于Affinity Propagation的python模块。该代码位于此链接。 https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/affinity_propagation_.py#L256

我已获取代码,并将其放置在名为affinitypropagationlib.py的文件中。

我正在尝试创建一个“主要” python模块,该模块导入上面的python文件,但收到以下错误。

Warning (from warnings module):
  File "C:\Users\Br. David Klecker\Downloads\WPy-3701\python-3.7.0.amd64\lib\site-packages\sklearn\utils\__init__.py", line 4
    from collections import Sequence
DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
Traceback (most recent call last):
  File "C:\Users\Br. David Klecker\Downloads\WPy-3701\notebooks\ap.py", line 4, in <module>
    import affinitypropagationlib
  File "C:\Users\Br. David Klecker\Downloads\WPy-3701\notebooks\affinitypropagationlib.py", line 12, in <module>
    from ..base import BaseEstimator, ClusterMixin
ImportError: attempted relative import with no known parent package

我为ap.py(主要的python模块)提供的代码如下。

import matplotlib.pyplot as plt
import numpy as np
#from sklearn.cluster import AffinityPropagation
import affinitypropagationlib
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs

# generating sampl data
centers = [[5, 5], [0, 0], [1, 5],[5, -1]]
X, labels_true =make_blobs(n_samples=500, n_features=5, centers=centers, cluster_std=0.9, center_box=(1, 10.0), shuffle=True, random_state=0)

# Compute Affinity Propagation
af = AffinityPropagation(max_iter=150, preference =-120).fit(X)
cluster_centers_indices = af.cluster_centers_indices_
labels = af.labels_

n_clusters_ = len(cluster_centers_indices)




#print results 
print('Estimated number of clusters: %d' % n_clusters_)
print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels))
print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels))
print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels))
print("Adjusted Rand Index: %0.3f"% metrics.adjusted_rand_score(labels_true, labels))
print("Adjusted Mutual Information: %0.3f"% metrics.adjusted_mutual_info_score(labels_true, labels))
print("Silhouette Coefficient: %0.3f"% metrics.silhouette_score(X, labels))


# Drawing chart
# Plot result
import matplotlib.pyplot as plt
from itertools import cycle

plt.close('all')
plt.figure(1)
plt.clf()

colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
for k, col in zip(range(n_clusters_), colors):
    class_members = labels == k
    cluster_center = X[cluster_centers_indices[k]]
    plt.plot(X[class_members, 0], X[class_members, 1], col + '.')
    plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
             markeredgecolor='k', markersize=14)
    for x in X[class_members]:
        plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col)

plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.show()

这是在affinitypropagationlib.py文件中出现错误的开头几行。

import numpy as np
import warnings

from sklearn.exceptions import ConvergenceWarning
from ..base import BaseEstimator, ClusterMixin
from ..utils import as_float_array, check_array
from ..utils.validation import check_is_fitted
from ..metrics import euclidean_distances
from ..metrics import pairwise_distances_argmin

我对正在发生的事情不知所措。我是python的新手,所以如果错误是基本的,我深表歉意。我的猜测是我仍然缺少被称为affinitypropagation.lib的库,也许很多库名称之前的两个点可能是线索。

1 个答案:

答案 0 :(得分:2)

感谢评论员的帮助,使我的工作成功了!解决方案是仅使用绝对导入而不是相对导入来包含库sklearn

所以不是

from ..base import BaseEstimator, ClusterMixin

只需使用

from sklearn.base import BaseEstimator, ClusterMixin.