简体   繁体   中英

How do I implement this import statement for Python?

I have a python module for Affinity Propagation I found online. The code is found here at this link. https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/affinity_propagation_.py#L256

I have taken the code and have placed in a file called affinitypropagationlib.py.

I am trying to create a "main" python module which imports the python file above but am receiving the following error.

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

The code I have for my ap.py (my main python module) is the following.

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()

Here are the opening lines in the affinitypropagationlib.py file where the error is happening.

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

I am at a loss to what is going on. I am VERY new to python so I apologize if the error is basic. My guess is I am still missing libraries which are called for affinitypropagation.lib and perhaps the two dots before many of the library names might be the clue.

I got this to work thanks to the help of the commentors! The solution is to simply include the library sklearn using absolute instead of relative imports.

So instead of

from ..base import BaseEstimator, ClusterMixin

just use

from sklearn.base import BaseEstimator, ClusterMixin. 

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