Cannot import mean from statistics - python

I'm trying to import statistics module in python. It's giving me an error message when i execute the program.
Here is my code:
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
xs = np.array([1,2,3,4,5,6,7,8])
ys = np.array([2,8,5,0,5,7,3,6])
def best_fit_line(xs ,ys):
m = ( ((mean(xs)* mean(ys))- mean(xs*ys)) /
(mean(xs)*mean(xs))-(mean(xs*xs)))
return m
m = best_fit_line(xs,ys)
The error message:
Traceback (most recent call last):
File "/home/kudzai/Documents/Machine Learning/LinearRegAlg.py", line 1, in <module>
from statistics import mean
ImportError: No module named statistics

The statistics module was added in Python 3.4. Perhaps you're using an older Python version.
If you can't upgrade for whatever reason, you can also just use numpy's mean function: np.mean(xs) etc. For numpy arrays, it's probably faster too.

Related

ImportError when using trackviz module

I'm assigned to run a python script, that imports several module
#filename: animate_vid_v6.py
import numpy as np
import pandas as pd
import imageio
from trackviz import animate
import sys
from matplotlib.patches import Circle
from operator import itemgetter
import colorsys
after I installed all the required modules, I get this error message.
Traceback (most recent call last):
File "<some_directories>\animate_vid_v6.py", line 4, in <mo
dule>
from trackviz import animate
File "C:\Python39\lib\site-packages\trackviz\animate.py", line 9, in <module>
from trackviz.tools import FigureAxes
File "C:\Python39\lib\site-packages\trackviz\tools.py", line 3, in <module>
from mpl_toolkits.axes_grid1 import Divider, LocatableAxes, Size
ImportError: cannot import name 'LocatableAxes' from 'mpl_toolkits.axes_grid1' (
C:\Python39\lib\site-packages\mpl_toolkits\axes_grid1\__init__.py)
After I scrutinize that message, it is turn out that the LocatableAxes is no longer exists in scripts inside the C:\Python39\lib\site-packages\mpl_toolkits\axes_grid1 directory.
As you can see here, at the C:\Python39\lib\site-packages\mpl_toolkits\axes_grid1\__init__.py, there are no LocatableAxes module.
from . import axes_size as Size
from .axes_divider import Divider, SubplotDivider, make_axes_locatable
from .axes_grid import Grid, ImageGrid, AxesGrid
from .parasite_axes import host_subplot, host_axes
Does anybody has an idea /suggestions to fix this problem? thanks.
The LocatableAxes classes have been deprecated in Matplotlib 3.0.0, but it seems trackviz hasn't been updated since then to avoid using these classes. Indeed, the trackviz GitHub repository hasn't been updated for about three years.
If you really want to use trackviz you will have to install an older version of Matplotlib.

Cannot import a function from a module in python

I'm using this code.
from azlyrics import artists
print(artists("O"))
In the module named 'azlyrics' the function 'artists' is well defined. But I get this error.
Traceback (most recent call last):
File "C:\Users\user\Desktop\python\eminem\New folder\azlyrics-master\examples\get_artists.py", line 1, in <module>
from azlyrics import artists
ImportError: cannot import name 'artists' from 'azlyrics' (C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\azlyrics\__init__.py)
What could be the problem?
There must be a bug in the azlyrics documentation or packaging.
This works:
>>> from azlyrics.azlyrics import artists
>>> artists("O")
'["Oakenfold, Paul", "Oakes, Ryan", "Oak Ridge Boys,
The", "Oak, Winona", "O.A.R. (Of A Revolution)", "Oasis", "Obel, Agnes", "Oberst, ...]'
There is a mistake in azlyrics v1.3.2, relative import should be used in azlyrics/__init__.py:
instead of:
from azlyrics import *
we should have:
from .azlyrics import *
This is fixed but a release is not done.

Audio analysis with python + octave

i want to analysis audio files with Python and Octave. Acutally i am getting an error
Traceback (most recent call last):
File "C:/Users/peter/PycharmProjects/AudioTools/ShutterTest.py", line 11, in <module>
(peaks, indexes) = octave.findpeaks(np.array(test), 'DoubleSided')
ValueError: not enough values to unpack (expected 2, got 1)
my Code is:
import numpy as np
from matplotlib import pyplot as plt
from scipy.io import wavfile
from oct2py import octave
samplerate, data = wavfile.read("TestWav.wav")
cb = np.array(data, dtype=np.int16)
test =[d[0] for d in cb]
octave.eval("pkg load signal")
(peaks, indexes) = octave.findpeaks(np.array(test), 'DoubleSided')
plt.plot(peaks)
plt.show()
Can someone give an advise?
Thanks
Since the version 4.0.0 of oct2py (see release notes here), it is necessary to provide an nout argument when requiring more outputs.
So in your case you have to do:
(peaks, indexes) = octave.findpeaks(np.array(test), 'DoubleSided', nout=2)

math built-in functions 'log'

I want to work with logarithms, but my math module doesn't work like it is supposed to.
Here's my code:
import math
n= int(2)
x = n**2
y = 2*n** log(3,2) +1
while float(x) < float(y):
n += 1
print(n)
It prints the following Error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\python\exp102.py", line 72, in <module>
y = 2*n** log(3,2) +1
NameError: name 'log' is not defined
Can you help me put the math module work perfectly, if that's the problem?
If you want to use a function from a package, you have several options to do that. The two most use:
from math import log
This will make log available in the namespace and you can use it directly.
import math
This will make math available and you can access the function as math.log().
Try to import log module with below statement:
from math import log.

Scipy installation, its installed why the traceback?

I am running the following code (this is the beginning snippet):
# Import necessary modules and functions
########################################
# time module, for timing it.
from time import time
global starttime
starttime = time()
# psutil for indentifying processor and memory usage
#import psutil
# csv module for loading csv files
import csv
# numpy, a standard module for working with arrays
import numpy as np
# for randomly shuffling arrays
from random import shuffle
# for computing mean squared errors
from sklearn import metrics
# importing modules that contain models we will use
from sklearn import linear_model, ensemble, gaussian_process
from sklearn import neural_network, svm
# importing memory profiler to enable us to determine peak memory usage
from memory_profiler import profile
# Helpful functions
###################
#psutilpercent = psutil.virtual_memory()
#print "\n", " --> Memory Check 1 Percent:", str(psutilpercent.percent) + "%\n"
# This function is for simplifying reading CSV files
def readCSV(path):
"""
Read a CSV file of floats, with no headder
"""
data = []
mycsv = csv.reader(open(path), delimiter="|")
for counter, row in enumerate(mycsv):
if counter != 0:
data.append(row)
return np.asarray(data, dtype=np.float32)
However I am receiving the traceback:
Traceback (most recent call last):
File "C:\Users\regression_v6.py", line 38, in <module>
from sklearn import metrics
File "C:\Python27\lib\site-packages\sklearn\__init__.py", line 32, in <module>
from .base import clone
File "C:\Python27\lib\site-packages\sklearn\base.py", line 10, in <module>
from scipy import sparse
ImportError: No module named scipy
But my computer shows Scipy as installed, here is a view of Control Panel\All Control Panel Items\Programs and Features:
Any ideas?
Did you install a special version of scipy? as your screenshot shows 'scipy_umfpack'
I can successfully import sklearn using the official version downloaded from sourceforge: http://sourceforge.net/projects/scipy/files/scipy/

Categories

Resources