Python not recognizing sub module in Jupyter - python

I have a problem using python module in Jupyter. It was working fine until yesterday. The only new thing is that I updated Seaborn to th elatest version. I do not have the pb when I use Spyder directly.
For exemple, I have a file that would be like :
import numpy as np
import pandas as pd
import scipy
def test_skewn(TimeSeries):
tempTimeSeries = TimeSeries.copy()
temp_Rolling_Perf = (tempTimeSeries / tempTimeSeries.shift(1) -1 ).dropna()
current_skew = scipy.stats.skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
return(current_skew )
I work perfectly from Spyder but from Jupyter it return :
AttributeError: module 'scipy' has no attribute 'stats'
If I correct it like this :
import numpy as np
import pandas as pd
#import scipy
from scipy.stats import skew, kurtosis
def test_skewness(TimeSeries):
tempTimeSeries = TimeSeries.copy()
temp_Rolling_Perf = (tempTimeSeries / tempTimeSeries.shift(1) -1 ).dropna()
#current_skew = scipy.stats.skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
current_skew = skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
return(current_skew )
It works in Jupyter.
It was working with both version before and I am not confortable at all with this pb and I would like to understand where it can come from.

Related

Jupyter imported module not using library

I made an external module model.py and I want to import it within my Jupyter notebook.
# model.py
import numpy as np
import pandas as pd
from scipy.stats import chi2
from sklearn.covariance import EllipticEnvelope
from sklearn.base import BaseEstimator
from scipy.stats import combine_pvalues
# ...
def predict(self, xtest):
return np.where(self.predict_proba(xtest, False) < self.critical_value, 1., -1.)
When I try to call the predict method of my model class I get the error:
NameError: name 'np' is not defined.
I have the numpy library installed and I am strugggling to understand why it is not able to use it.
Any ideas?

modulenotfounderror: no module named 'sklearn.linear_model.logistic' on python flask

I had a problem running my http://127.0.0.1:5000/iris/1/1/1/1. It keeps getting an internal server error. I don't know why and It kept doing it. I tried many ways but it still didn't work. Its kept saying "modulenotfounderror: no module named 'sklearn.linear_model.logistic' ." Is there a way to resolve this.
from flask import Flask, render_template
from flask import jsonify
from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from mpl_toolkits import mplot3d
from sklearn.datasets import load_iris
from sklearn import datasets
import csv
import joblib
app = Flask(__name__)
def predict(sepal_length, sepal_width, petal_length, petal_width):
test_data = np.array([sepal_length, sepal_width, petal_length,petal_width])
test_data = test_data.reshape(1,-1)
file = open("data/iris.pkl","rb")
trained_model = joblib.load(file)
prediction = trained_model.predict(test_data)
return prediction
#app.route("/iris/<sepal_length>/<sepal_width>/<petal_length>/<petal_width>")
def iris(sepal_length, sepal_width, petal_length, petal_width):
result=predict(np.double(sepal_length),
np.double(sepal_width),
np.double(petal_length),
np.double(petal_width))
if result[0]==0:
hasil='Setosa'
elif result[0]==1:
hasil='Versicolor'
else:
hasil='Virginica'
return hasil
Check the version of scikit-learn, maybe it is 0.21.x. upgrade the version.
Here is scikit-learn stable:
https://github.com/scikit-learn/scikit-learn/tree/master/sklearn/linear_model

package import is not importing its dependencies

I just wrote a small package containing a class to use on jupyter labs at work, however when I try to import and use the class which is dependent on numpy and matplotlib, it says that np is not defined.
Even though it is imported into the file I am importing the class into, and I imported it into the class file itself that I am importing, and the __init__.py file for the package. I just need the class to load some data into a np.array([]) via np.genfromtxt().
I have made one package before and didn't have any issues but I'm new so am obviously missing something.
Here's how I get the error:
pip install git+https://github.com/Elliot-Wadge/pl_class#egg=pl_class
import numpy as np
import matplotlib.pyplot as plt
import glob
from pl_data import pl_data as pl
PL_data = pl.PL_data
flist = glob.glob("data/*")
dictionary = PL_data(flist, skip_header = 4, unpack = True, delimiter = '\t')
error message
class file

Cannot import class from module (circular reference issue?)

I've seen countless issues here on stack about this but still can't figure out why I cant get mine to work. I have a 2 .ipynb files and I'm looking to import a class from one file to the other as follows:
CV_Screening_Interface:
from joblib import dump, load
import sys
import pandas as pd
import os
import import_ipynb
import docx
import readDocx ***(This is another ipynb file)***
from docx import Document
import string
model = load('model.joblib')
class CV:
def __init__(self,university,major,masters,company,certification,GPA):
self.university = university
self.major = major
self.masters = masters
self.company = company
self.certification = certification
self.GPA = GPA
#And a bunch of other functions
Now in FirstProgram
from tkinter import *
from tkinter import filedialog
from docx import Document
import io
import import_ipynb
import CV_Screening_Interface
#Till here works fine
When I try to import class CV I get an import error
from CV_Screening_Interface import CV
OR
test = CV_Screening_Interface.CV()
ImportError: cannot import name 'CV' from 'CV_Screening_Interface' (CV_Screening_Interface.ipynb)
I checked PYTHONPATH, I have an empty init.py in the directory already. What's weird is that importing the module works, but importing the class in the module doesn't.
Note in CV_Screening_Interface CV class works perfectly fine so I don't think there is any issue with it specifically. Probably need a if name="main" inside it?
Ok so this solved my problems:
I created a new ipynb called ClassFile.ipynb and it only contains the Class CV without importing any packages
Then i converted ClassFile.ipynb to ClassFile.py and imported it to FirstProgram and it worked.

Print version of a module without importing the entire package

Is it possible to check the version of a package if only a module is imported?
When a package is imported like...
import pandas as pd
I use:
print('pandas : version {}'.format(pd.__version__))
to print the version number.
How do I check the version number if only a module is imported, like
import matplotlib.pyplot as plt
or
from sklearn.metrics import confusion_matrix
Any suggestions?
I usually do this:
import matplotlib.pyplot as plt
import sys
print (sys.modules[plt.__package__].__version__)
if you import just a function:
from sklearn.metrics import confusion_matrix as function
import sys
try:module_name = function.__module__[:function.__module__.index(".")]
except:module_name = function.__module__
print (sys.modules[module_name].__version__)
and if this doesn't work you could just import pip and for loop all the modules.

Categories