Cannot get a SIMPLE HISTOGRAM to plot in Python 3.7 Notebook - python

Below is the error code I received as I am trying to do a Histogram from the DF "code" and the column ("Age")
code['Age'].plt.hist()
1
code['Age'].plt.hist()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-44-2117f9d17105> in <module>
----> 1 code['Age'].plt.hist()
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5177 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5178 return self[name]
-> 5179 return object.__getattribute__(self, name)
5180
5181 def __setattr__(self, name, value):
AttributeError: 'Series' object has no attribute 'plt'

Use the hist function directly from matplotlib:
import matplotlib.pyplot as plt
plt.hist(code['Age'])
plt.show()
This should work. You can also do:
import matplotlib.pyplot as plt
code['Age'].hist()
plt.show()

Related

AttributeError: module 'tensorflow._api.v1.config' has no attribute 'run_functions_eagerly'

Trying to run ImageAI in Jupyter.
I'm getting the following error
Using TensorFlow backend.
AttributeError Traceback (most recent call last)
in
----> 1 from imageai.Detection.Custom import DetectionModelTrainer
~\anaconda3\envs\ImageAI\lib\site-packages\imageai\Detection\Custom_init_.py in
19 import cv2
20
---> 21 tf.config.run_functions_eagerly(True)
22 os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
23
~\anaconda3\envs\ImageAI\lib\site-packages\tensorflow_core\python\util\module_wrapper.py in getattr(self, name)
191 def getattr(self, name):
192 try:
--> 193 attr = getattr(self._tfmw_wrapped_module, name)
194 except AttributeError:
195 if not self._tfmw_public_apis:
AttributeError: module 'tensorflow._api.v1.config' has no attribute 'run_functions_eagerly
What is the issue here?
Thanks in advance
You can try like this:
import tensorflow.compat.v1 as tf
tf.config.experimental_run_functions_eagerly(True)
#tf.function
def fn():
# `enter code here

Pandas TypeError: unhashable type: 'slice' / 'DataFrame' object has no attribute 'flatten'

I have written the following pandas/sklearn algorithm to predict the movie genre based on words occuring in the movie. Find the dataset here
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
data=pd.read_csv('movies.csv',sep=',');
df1 = data[["marri", "huh", "hous", "mother", "nice", "home", "miss", "play", "happi", "write","wouldnt","power", "captain", "ship", "weve", "move", "ship", "system", "world", "command", "three"]]
predicted_genre=data[["Genre"]]
X = np.c_[np.ones((df1.shape[0], 1)), df1]
predicted_genre = predicted_genre[:, np.newaxis]
Here, the error occurs but I included the code below since it is relevant for the second error:
theta = np.zeros((X.shape[1], 1))
model = LogisticRegression()
model.fit(X, predicted_genre.values.ravel())
parameters = model.coef_
predicted_classes = model.predict(X)
accuracy = accuracy_score(predicted_genre.flatten(),predicted_classes)
This is the error I observe:
TypeError Traceback (most recent call last)
<ipython-input-48-1b8359fe335e> in <module>
12 #model.fit(df1, predicted_genre)
13 X = np.c_[np.ones((df1.shape[0], 1)), df1]
---> 14 predicted_genre = predicted_genre[:, np.newaxis]
15 theta = np.zeros((X.shape[1], 1))
16 model = LogisticRegression()
/srv/app/venv/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
2686 return self._getitem_multilevel(key)
2687 else:
-> 2688 return self._getitem_column(key)
2689
2690 def _getitem_column(self, key):
/srv/app/venv/lib/python3.6/site-packages/pandas/core/frame.py in _getitem_column(self, key)
2693 # get column
2694 if self.columns.is_unique:
-> 2695 return self._get_item_cache(key)
2696
2697 # duplicate columns & possible reduce dimensionality
/srv/app/venv/lib/python3.6/site-packages/pandas/core/generic.py in _get_item_cache(self, item)
2485 """Return the cached item, item represents a label indexer."""
2486 cache = self._item_cache
-> 2487 res = cache.get(item)
2488 if res is None:
2489 values = self._data.get(item)
TypeError: unhashable type: 'slice'
When not including this line: predicted_genre = predicted_genre[:, np.newaxis] I get this error:
--------------------------------------------------------------------------- AttributeError
Traceback (most recent call last) <ipython-input-49-0fede056d645>
in <module>
18 parameters = model.coef_
19 predicted_classes = model.predict(X) --->
20 accuracy = accuracy_score(predicted_genre.flatten(),predicted_classes)
21 parameters /srv/app/venv/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name) 4374 if self._info_axis._can_hold_identifiers_and_holds_name(name): 4375 return self[name] -> 4376 return object.__getattribute__(self, name) 4377 4378 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'flatten'
Thank you for your help!

.idmin() and .idmax() in a Series not working

I am learning about python/pandas attributes in a Series. I can get it to display the min and max values, but I want to display the min and max index values and I get an error message.
google.min()
49.95
google.max()
782.22
google.idmin()
AttributeError Traceback (most recent
call last) in
----> 1 google.idmin(True)
/opt/anaconda3/envs/pandas_playground/lib/python3.8/site-packages/pandas/core/generic.py
in getattr(self, name) 5272 if
self._info_axis._can_hold_identifiers_and_holds_name(name): 5273
return self[name]
-> 5274 return object.getattribute(self, name) 5275 5276 def setattr(self, name: str, value) -> None:
AttributeError: 'Series' object has no attribute 'idmin'
After some searching, I found I was simply using the wrong methods.
idxmin and idxmax work just fine.
google.idxmax()
3011
google.idxmin()
11

NumpyBackend' object has no attribute 'tucker'

I have some codes for doing image compression using svd and some more codes for experiments.
So I have the following code for experiment:
plt.figure(figsize=(20,12))
for i,rank in enumerate([2,10,20]):
plt.subplot(2,3,i+1)
plt.imshow(svd_compression(image1,rank))
plt.title("rank:%i - compression: %.2f%%" %(rank,svd_compress_ratio(image1,rank)*100))
for i,rank in enumerate([2,10,20]):
plt.subplot(2,3,i+4)
plt.imshow(svd_compression(image2,rank))
plt.title("rank:%i - compression: %.2f%%" %(rank,svd_compress_ratio(image2,rank)*100))
plt.show()
But I got the following errors:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorly/backend/__init__.py in _get_backend_method(key)
91 try:
---> 92 return getattr(_LOCAL_STATE.backend, key)
93 except AttributeError:
AttributeError: 'NumpyBackend' object has no attribute 'tucker'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
3 frames
/usr/local/lib/python3.6/dist-packages/tensorly/backend/__init__.py in _get_backend_method(key)
92 return getattr(_LOCAL_STATE.backend, key)
93 except AttributeError:
---> 94 return getattr(_LOADED_BACKENDS[_DEFAULT_BACKEND], key)
95
96 def _get_backend_dir():
AttributeError: 'NumpyBackend' object has no attribute 'tucker'
The method for compression is here:
!pip install tensorly
import numpy as np
import pylab as plt
import scipy.sparse.linalg
import PIL.Image
import tensorly as tl
import matplotlib.pyplot as plt2
from scipy.sparse.linalg import svds
def svd_compression(image, rank):
unfolded = tl.unfold(image, mode=0)
u, s, vt = svds(unfolded, rank)
return tl.fold(np.round(np.dot(u*s,vt),1), 0, image.shape) # need to round to have a color lvl

'DataFrame' object has no attribute 'to_frame'

I am new to python. Just following the tutorial: https://www.hackerearth.com/practice/machine-learning/machine-learning-projects/python-project/tutorial/
This is the dataframe miss:
miss = train.isnull().sum()/len(train)
miss = miss[miss>0]
miss.sort_values(inplace = True)
miss
Electrical 0.000685
MasVnrType 0.005479
MasVnrArea 0.005479
BsmtQual 0.025342
BsmtCond 0.025342
BsmtFinType1 0.025342
BsmtExposure 0.026027
BsmtFinType2 0.026027
GarageCond 0.055479
GarageQual 0.055479
GarageFinish 0.055479
GarageType 0.055479
GarageYrBlt 0.055479
LotFrontage 0.177397
FireplaceQu 0.472603
Fence 0.807534
Alley 0.937671
MiscFeature 0.963014
PoolQC 0.995205
dtype: float64
Now I just want to visualize those missing values"
#visualising missing values
miss = miss.to_frame()
miss.columns = ['count']
miss.index.names = ['Name']
miss['Name'] = miss.index
And this is the error I got:
AttributeError Traceback (most recent call last)
<ipython-input-42-cd3b25e8862a> in <module>()
1 #visualising missing values
----> 2 miss = miss.to_frame()
C:\Users\Username\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
2742 if name in self._info_axis:
2743 return self[name]
-> 2744 return object.__getattribute__(self, name)
2745
2746 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'to_frame'
What am I missing here?
Check print(type(miss)) it should be <class 'pandas.core.series.Series'>
You have is dataframe, somewhere in the code you are doing wrong.
df = pd.DataFrame()
df.to_frame()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Users\UR_NAME\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 3614, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'to_frame'
I traced the tutorial, and below is the order flow
train = pd.read_csv("train.csv")
print(type(train)) # <class 'pandas.core.frame.DataFrame'>
miss = train.isnull().sum()/len(train)
print(type(miss)) # <class 'pandas.core.series.Series'>
miss = train.isnull().sum()/len(train) converts in into pandas.core.series.Series from pandas.core.frame.DataFrame
You are probably messed code at this place.
If you use Notebook while the current cell is running, "miss" is converted to a data frame so that the output is displayed the first time. If you run the cell again, you will get an/the error because it is already a data frame. So run the previous cell again and then run the current cell to fix the problem. The notebook itself works this way.

Categories

Resources