Print version of a module without importing the entire package - python

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.

Related

Cannot import name 'functional_datapipe' from 'torch.utils.data'

When I am running datasets_utils.py from '/usr/local/lib/python3.7/dist-packages/torchtext/data/datasets_utils.py' in Google Colab, the following error occurs even with the most updated versions of Python packages:
ImportError: cannot import name 'functional_datapipe' from 'torch.utils.data' (/usr/local/lib/python3.7/dist-packages/torch/utils/data/init.py)
Are there any solutions to solve such errors, as I could not find functional_datapipe even in the official torch.utils.data documentation? The following is excerpt from datasets._utils.py in the Google Colab environment
import functools
import inspect
import os
import io
import torch
from torchtext.utils import (
validate_file,
download_from_url,
extract_archive,
)
from torch.utils.data import functional_datapipe, IterDataPipe
from torch.utils.data.datapipes.utils.common import StreamWrapper
import codecs
It might be available only on torchdata.datapipes

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

how to call a module in a function in pp where that fuction has other functions in it?

I'm currently using parallel python ,and in the parameters of job_server.submit i added the library in modules but the problem is that even that library has other librairies in it .so what should i do ?
Here is the code i'm trying to run:
from tools.demo import detect_cn
import pp
job_server = pp.Server()
f1 = job_server.submit(detect_cn, (filename,),modules=('tools.demo',))
f2 = job_server.submit(detect_cn, (filename1,),modules=('tools.demo',))
cnis, preproc_time, roi_file_images=f1()
cnis1, preproc_time1, roi_file_images1=f2()
and this is part of code of demo.py
import _init_paths
from fast_rcnn.config import cfg
from fast_rcnn.test import im_detect
from fast_rcnn.nms_wrapper import nms
from utils.timer import Timer
from ocr.clstm import clstm_ocr
from ocr.clstm import clstm_ocr_calib
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import caffe, os, sys, cv2
import argparse
import werkzeug
import datetime
import math
import pytesseract
from PIL import Image
def detect_cn(filename):
cfg.TEST.HAS_RPN = True # Use RPN for proposals
args = parse_args()
prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0],
'faster_rcnn_alt_opt', 'faster_rcnn_test.pt')
caffemodel = os.path.join(cfg.DATA_DIR, 'faster_rcnn_models',
NETS[args.demo_net][1])
if not os.path.isfile(caffemodel):
raise IOError(('{:s} not found.\nDid you run ./data/script/'
'fetch_faster_rcnn_models.sh?').format(caffemodel))
if args.cpu_mode:
caffe.set_mode_cpu()
else:
caffe.set_mode_gpu()
caffe.set_device(args.gpu_id)
cfg.GPU_ID = args.gpu_id
net = caffe.Net(prototxt, caffemodel, caffe.TEST)
print '\n\nLoaded network {:s}'.format(caffemodel)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Demo for CN image...'
return demo2(net, filename)
Do you think i should load all those librairies in modules of job server.submit?
I want to use the pp bacause detect_cn takes 2 minutes to give results
any ideas?
Yes, you should import all these modules when wou submit your function into the execution queue.
f1 = job_server.submit(detect_cn, (filename,),modules=("math","numpy", ...))

Python printing a string yields an unexpected result

Trying to print / work with a specific String is driving me crazy in Python - or to specify this: I am using Jython.
The simple command
print "appilog.xxxxx.xxxxx.xxxxxxx"
results in a print of something looking like a java package
com.xxxxx.xxxxx.xxxxxx
Does Python/Jython do any special lookup for strings? Is there a way to enforce the usage of the "original" string I entered before?
Other things I tried are the following:
print ("appilog...")
print r"appilog..."
print str("appilog...")
print str(r"appilog...")
Imports used in the script this command is located in are the following:
from com.hp.ucmdb.discovery.probe.services.dynamic.core import EnvironmentInformation
#coding=utf-8
import string
import re
import sys
import os
import ConfigParser
import shutil
import StringIO
import logger
import modeling
import time
import subprocess
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import datetime
from appilog.common.system.types.vectors import ObjectStateHolderVector

Categories