ImportError: cannot import name 'structural_similarity' error - python-3.x

In my image comparision code following: https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/
While using
from skimage.measure import structural_similarity as ssim
and then
s = ssim(imageA, imageB)
I am getting error:
from skimage.measure import structural_similarity as ssim
ImportError: cannot import name 'structural_similarity'

I found the solution. As this question is unique and not covered anywhere. So, posting the answer.
#from skimage.measure import structural_similarity as ssim
from skimage import measure
.
.
.
#s = ssim(imageA, imageB)
s = measure.compare_ssim(imageA, imageB)
Change commented line to uncommented line.

Please check your skimage version.
https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.compare_ssim
Changed in version 0.16: This function was renamed from skimage.measure.compare_ssim to skimage.metrics.structural_similarity.
Hope it helps.

change import line to
from skimage.metrics import structural_similarity as ssim
This may work better than using compare_ssim since that is going to be deprecated

I use next solution:
from skimage import metrics
metrics.structural_similarity(grayA, grayB, full=True)

Related

NameError: name 'pairwise_distances_argmin' is not defined

Upon running this code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
from sklearn.datasets import make_blobs
X, y_true = make_blobs(n_samples = 300, centers= 4, cluster_std =0.60,random_state = 0)
plt.scatter(X[:,0], X[:,1], s=50)
labels = pairwise_distances_argmin(X, centres)
I am getting a NameError
"name 'pairwise_distances_argmin' is not defined"
What may be the possible reasons for it.
Please note that I am relatively new to this field, elaborated answers are most welcome.
Thanks in advance.
Have searched Stack overflow and unsuccessfully try solutions suggested on these pages:
Weird results of sklearn.metrics.pairwise_distances_argmin_min when computing euclidean distance
NameError: name 'sklearn' is not defined
You wish to use the
pairwise_distances_argmin
function.
You're going to have to import it:
from sklearn.metrics import pairwise_distances_argmin

Having issues with sys.argv()

I'm new to python programming and trying to implement a code using argv(). Please find the below code for your reference. I want to apply filter where Offer_ID = 'O456' with the help of argv().
Code:
-----
import pandas as pd
import numpy as np
import string
import sys
data = pd.DataFrame({'Offer_ID':["O123","O456","O789"],
'Offer_Name':["Prem New Ste","Prem Exit STE","Online Acquisiton Offer"],
'Rule_List':["R1,R2,R4","R6,R2,R3","R10,R11,R12"]})
data.loc[data[sys.argv[1]] == sys.argv[2]] # The problem is here
print(data)
With this statement I'm getting the output -> "print(data.loc[data['Offer_ID'] =='O456'])"
but I want to accomplish it as shown here "data.loc[data[sys.argv[1]] == sys.argv[2]]" .
Below is the command line argument which I'm using.
python argv_demo2.py Offer_ID O456
Kindly assist me with this.
I'm a little confused as to what the issue is, but is this what you're trying to do?
import pandas as pd
import numpy as np
import string
import sys
data = pd.DataFrame({'Offer_ID':["O123","O456","O789"],
'Offer_Name':["Prem New Ste","Prem Exit STE","Online Acquisiton Offer"],
'Rule_List':["R1,R2,R4","R6,R2,R3","R10,R11,R12"]})
select = data.loc[data[sys.argv[1]] == sys.argv[2]] # The problem is here
print(select)

ModuleNotFoundError: No module named 'pandas.lib'

from ggplot import mtcars
While importing mtcars dataset from ggplot on jupyter notebook i got this error
My system is windows 10 and I've already reinstalled and upgraded pandas (also used --user in installation command)but it didn't work out as well. Is there any other way to get rid of this error?
\Anaconda3\lib\site-packages\ggplot\stats\smoothers.py in
2 unicode_literals)
3 import numpy as np
----> 4 from pandas.lib import Timestamp
5 import pandas as pd
6 import statsmodels.api as sm
ModuleNotFoundError: No module named 'pandas.lib'
I Just tried out a way. I hope this works out for others as well. I changed from this
from pandas.lib import Timestamp
to this
from pandas._libs import Timestamp
as the path of the module is saved in path C:\Users\HP\Anaconda3\Lib\site-packages\pandas-libs
is _libs
Also, I changed from
date_types = (
pd.tslib.Timestamp,
pd.DatetimeIndex,
pd.Period,
pd.PeriodIndex,
datetime.datetime,
datetime.time
)
to this
date_types = (
pd._tslib.Timestamp,
pd.DatetimeIndex,
pd.Period,
pd.PeriodIndex,
datetime.datetime,
datetime.time
)
Before that, I went on this path "C:\Users\HP\Anaconda3\Lib\site-packages\ggplot\util.py" to make the same changes in util.py for date_types. This helped me out to get rid of the error I mentioned in my question.

JPype error: import jpype ModuleNotFoundError: No module named 'jpype'

I installed JPype in a correct way and anything is fine and my instalation was succeed but when i run my refactor.py from command prompt i have error that i pointed in title.
i hope you can help me for solving this problem.
also i have to point that i am beginner in python3.
here is my code:
import urllib.request
import os
import tempfile
import sys
import fileinput
import logging
import jpype
logging.basicConfig(filename="ERROR.txt", level= logging.ERROR)
try:
logging.debug('we are in the main try loop')
jpype.startJVM("C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest.java", "-ea")
test_class = jpype.JClass("ClassWithTest")
a = testAll()
file_java_class = open("OUTPUT.txt", "w")
file_java_class.write(a)
except Exception as e1:
logging.error(str(e1))
jpype.shutdownJVM()
startJVM() function takes the path to the JVM which is like this - C:\\Program Files\\Java\\jdk-10.0.2\\bin\\server\\jvm.dll. You could use the getDefaultJVMPath() function to get the JVM path on your PC. So you can just start the JVM this way:
startJVM(getDefaultJVMPath(), "-ea")
Hope that helps!

Why is my image_path undefined when using export_graphviz? - Python 3

I'm trying to run this machine learning tree algorithm code in IPython:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target
tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X, y)
from sklearn.tree import export_graphviz
export_graphviz(tree_clf, out_file=image_path("iris_tree.dot"),
feature_names=iris.feature_names[2:],
class_names=iris.target_names,
rounded=True,
filled=True
)
But I get this error when run in IPython:
I'm unfamiliar with export_graphviz, does anyone have any idea how to correct this?
I guess you are following "Hands on Machine Learning with Scikit-Learn and TensorFlow" book by Aurelien Geron. I encountered with the same problem while trying out "Decision Trees" chapter. You can always refer to his GitHub notebooks . For your code, you may refer "decision tree" notebook.
Below I paste the code from notebook. Please do go ahead and have a look at the notebook also.
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "decision_trees"
def image_path(fig_id):
return os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID, fig_id)
def save_fig(fig_id, tight_layout=True):
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(image_path(fig_id) + ".png", format='png', dpi=300)
To get rid of all the mess simply remove image_path,
now out_file="iris_tree.dot", after running that command a file will be saved in your folder named iris_tree. Open that file in Microsoft Word and copy all of its content. Now open your browser and type "webgraphviz" and then click on the first link. Then delete whatever is written in white space and paste your code which is copied from iris_tree. Then click "generate graph". Scroll down and your graph is ready.
I know you might have got what you were looking for. But in case you don't, all you need to do is just replace:
out_file=image_path("iris_tree.dot")
with:
out_file="iris_tree.dot"
This will create the .dot file in the same directory in which your current script is.
You can also give the absolute path to where you want to save the .dot file as:
out_file="/home/cipher/iris_tree.dot"
you must correct
out_file=image_path("iris_tree.dot"),
in below code line:
out_file="C:/Users/VIDA/Desktop/python/iris_tree.dot",
You can directly type instead of using the webgraphviz, if you are using sklearn version 0.20.
import graphviz
with open ("iris_tree.dot") as f:
dot_graph = f.read()
display (graphviz.Source(dot_graph))
With sklearn 0.22 you have to change again. See sklearn users guide.
I have a sklearn with the version of 0.20.1, and I got the example to work through the line below.
export_graphviz(
tree_clf,
out_file = "iris_tree.dot",
feature_names = iris.feature_names[2:])

Resources