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

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

Related

Importing transformers, evaluate, or torch python library and Internal Server Error 500

It seems that when I call a python function from an xmlhttp request so that its output prints to the browser, the script will lead to an error if any of these import statements (commented) are run:
import traceback
import transformers
"""
from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification, TrainingArguments, Trainer
import evaluate
import torch
"""
import pandas as pd
import numpy as np
import datasets
from datasets import load_dataset, load_metric, load_from_disk, Value
import cgi, cgitb
print("Content-Type: text/html\n")
print("Hello!")
That is, if I keep them commented, my hello statement will show on the browser, otherwise, I get an internal server error 500. Any help would be greatly appreciated!!
I already tried suppressing warnings and logs!

No module named 'sklearn.neighbors.base' still existed after all the suggestions what I can take

I learned a lot of solutions from this website, but still cannot solve the problem. My code is as follows for your review:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno
import altair as alt
from statsmodels.graphics.mosaicplot import mosaic
from scipy.stats import chi2_contingency
import plotly.express as px
from pandas.plotting import parallel_coordinates
from wordcloud import WordCloud
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
from scipy.spatial import distance
!pip install sklearn
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.impute import KNNImputer
from missingpy import MissForest
import sklearn.neighbors._base
sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
import warnings
warnings.filterwarnings("ignore")
And still shows the error: ModuleNotFoundError: No module named 'sklearn.neighbors.base' I've tried to do the follows:
pip install -U imbalanced-learn ;
pip install -U scikit-learn
ans there was still of no use
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11280/2643854484.py in <module>
26 from sklearn.impute import IterativeImputer
27 from sklearn.impute import KNNImputer
---> 28 from missingpy import MissForest
29 import sklearn.neighbors._base
30 sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
C:\ProgramData\Anaconda3\lib\site-packages\missingpy\__init__.py in <module>
----> 1 from .knnimpute import KNNImputer
2 from .missforest import MissForest
3
4 __all__ = ['KNNImputer', 'MissForest']
C:\ProgramData\Anaconda3\lib\site-packages\missingpy\knnimpute.py in <module>
11 from sklearn.utils.validation import check_is_fitted
12 from sklearn.utils.validation import FLOAT_DTYPES
---> 13 from sklearn.neighbors.base import _check_weights
14 from sklearn.neighbors.base import _get_weights
15
ModuleNotFoundError: No module named 'sklearn.neighbors.base'
Finally, I solved the problem!!
I should write this before import missingpy, not behind it.
import sklearn.neighbors._base
import sys
sys.modules['sklearn.neighbors.base'] = sklearn.neighbors._base
from missingpy import MissForest
done.

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?

Module 'dateutil' has no attribute 'parser' - Dateutil - Python

I am trying to download a pre-trained tensorflow model. I am using the below code
import numpy as np
import time
import PIL.Image
import IPython.display as display
import matplotlib.pylab as plt
import tensorflow as tf
import tensorflow_hub as hub
import datetime
from tensorflow.keras.preprocessing import image
from dateutil import parser
from keras.applications.inception_v3 import InceptionV3
model = InceptionV3()
model.summary()
I am getting the following error
AttributeError: module 'dateutil' has no attribute 'parser'
I am using python -3.7 and TF-2.7, python-dateutil-2.8.1
Please help me fix this. Thank You :)
The correct import syntax is:
import dateutil.parser
and then:
parser.parse(time_string)
or:
from dateutil.parser import parse
parse(time_string)
Documentation: https://dateutil.readthedocs.io/en/stable/parser.html

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