AttributeError: 'list' object has no attribute 'rgb2hex' - data-visualization

I am getting the error *" AttributeError: 'list' object has no attribute 'rgb2hex'" while trying to apply Kmeans clustering for my data and trying to map the clusters with folium *
map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11)
# set color scheme for the clusters
x = np.arange(kclusters)
ys = [i + x + (i*x)**2 for i in range(kclusters)]
colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))
rainbow = [colors.rgb2hex(i) for i in colors_array]
# add markers to the map
markers_colors = []
for lat, lon, poi, cluster in zip(banglore_merged['latitude'], banglore_merged['longitude'], banglore_merged['location'], banglore_merged['Cluster Labels']):
label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True)
folium.CircleMarker(
[lat, lon],
radius=5,
popup=label,
color=rainbow[int(cluster)-1],
fill=True,
fill_color=rainbow[int(cluster)-1],
fill_opacity=0.7).add_to(map_clusters)
map_clusters
ERROR:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-50-8e09b66c0be6> in <module>
6 ys = [i + x + (i*x)**2 for i in range(kclusters)]
7 colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))
----> 8 rainbow = [colors.rgb2hex(i) for i in colors_array]
9
10 # add markers to the map
<ipython-input-50-8e09b66c0be6> in <listcomp>(.0)
6 ys = [i + x + (i*x)**2 for i in range(kclusters)]
7 colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))
----> 8 rainbow = [colors.rgb2hex(i) for i in colors_array]
9
10 # add markers to the map
AttributeError: 'list' object has no attribute 'rgb2hex'
I hope you find the answer to my query. Thanks In advance

i guess you are passing an empty dataset to the variable. kindly change the Name.
rainbow = [colors.rgb2hex(i) for i in colors_array]

Related

AttributeError: 'DataFrame' object has no attribute 'Vmax'

I try to solve this problem:
AttributeError: 'DataFrame' object has no attribute 'Vmax'
This is a code:
plt.figure(figsize = (15,5))
plt.plot(data.indice_tiempo, data.Vmax, label = 'Precio máximo')
plt.plot(data.indice_tiempo, data.Vmin, label = 'Precio mínimo')
plt.legend()
plt.xlabel('Fecha')
plt.ylabel('Precio')
#plt.ylim(-10,40)
plt.show()
AttributeError Traceback (most recent call last)
<ipython-input-28-e6aa3f72c6f3> in <module>
1 plt.figure(figsize = (15,5))
2
----> 3 plt.plot(data.indice_tiempo, data.Vmax, label = 'Precio máximo')
4 #plt.plot(data.indice_tiempo, data.Vmin, label = 'Precio mínimo')
5 plt.legend()
/usr/local/lib/python3.8/dist-packages/pandas/core/generic.py in __getattr__(self, name)
5485 ):
5486 return self[name]
-> 5487 return object.__getattribute__(self, name)
5488
5489 def __setattr__(self, name: str, value) -> None:
AttributeError: 'DataFrame' object has no attribute 'Vmax'
I maybe need more info to help you but I guess you are trying to plot a line representing the price of something and point the max and min price.
You can try something like this:
#Create dummy data
data_dict = {"indice_tiempo":[24,25,21,31,32,21],
"fecha":["01/06","02/06","03/06","04/06","05/06","06/06"]}
data = pd.DataFrame(data_dict)
#Set column "fecha" as index
data = data.set_index("fecha")
#Create plot
plt.figure(figsize = (15,5))
max_data = data.indice_tiempo.sort_values(ascending=False).head(1) #Filter max price data
min_data = data.indice_tiempo.sort_values(ascending=False).tail(1) #Filter min price data
plt.plot(data.index, data.indice_tiempo) #Plot line
plt.scatter(max_data.index, max_data.values, label = 'Precio máximo') #Plot max price point
plt.scatter(min_data.index, min_data.values, label = 'Precio mínimo') #Plot min price point
plt.legend()
plt.xlabel('Fecha')
plt.ylabel('Precio')
plt.show()
The error you are getting from Python is telling you that you don't have any column called "Vmax" in your dataframe.
I guess you're trying to call a function to get the max price.
For that you need to do this --> df.column_name.max() or df["column_name"].max()
Resulting PLOT

How to use keys in defining integer_var_list for cplex?

I am not really sure about how to define a decision variable by using integer_var_list().
Supposing I have a set of scalar decision variables X = [[x1,x2,x3,x4,x5,x6]], then I defined them as:
'''
x = np.empty((Total_T,1), dtype= object)
for i in range(Total_T):
x[i] = mdl.integer_var(lb= 0, ub= inf, name='x' + str(i+1))
Then I will get X as follows (each x is scalar).
[[x1]
[x2]
[x3]
[x4]
[x5]
[x6]]
'''
However when I tried following code:
'''
x = np.empty((Total_T,1), dtype= object)
for i in range(Total_T):
x = mdl.integer_var_list(Total_T,lb= 0, ub= inf, name='x' + str(i+1))
I got an error notice below.
[docplex.mp.Var(type=I,name='x6_0'), docplex.mp.Var(type=I,name='x6_1'),
docplex.mp.Var(type=I,name='x6_2'), docplex.mp.Var(type=I,name='x6_3'),
docplex.mp.Var(type=I,name='x6_4'), docplex.mp.Var(type=I,name='x6_5')]
Traceback (most recent call last):
File "C:/Users/pknu/Documents/Research/project/MILP Case 1 19 July 2022.py", line 78, in
<module>
x_in = get_index_value(1) #number 1 for transition in
File "C:/Users/pknu/Documents/Research/project/MILP Case 1 19 July 2022.py", line 73, in
get_index_value
get_value = x[ind_x]
TypeError: list indices must be integers or slices, not tuple
'''
Can anyone let me know:
What are the keys in mdl.integer_var_list(keys, lb = None, ub=None, name =<class'str'>, key_format=None) and how to use it?
Can I define X as mdl.integer_var_list but contains x[i] as mdl.integer_var for i from 0 to Total_T=6?
Thank you.
Best regards,
Nicholas
Small integer_var_list example
from docplex.mp.model import Model
Buses=[
(40,500),
(30,400)
]
nbKids=300
nbSizes=len(Buses)
# Indexes
busSize=0;
busCost=1;
for b in Buses:
print("buses with ",b[busSize]," seats cost ",b[busCost])
mdl = Model(name='buses')
#decision variables
mdl.nbBus = mdl.integer_var_list(nbSizes,0,1000,name="nbBus")
# Constraint
mdl.add(sum(mdl.nbBus[b]*Buses[b][busSize] for b in range(0,nbSizes)) >= nbKids)
# Objective
mdl.minimize(sum(mdl.nbBus[b]*Buses[b][busCost] for b in range(0,nbSizes)))
msol=mdl.solve()
# Dislay solution
for b in range(0,nbSizes):
print(msol[mdl.nbBus[b]]," buses with ",Buses[b][busSize]," seats")

TypeError: descriptor 'lower' for 'str' objects doesn't apply to a 'list' object

I wanna stemming my dataset. Before stemming, I did tokenize use nltk tokenize
You can see the output on the pic
Dataset
Col Values
But when i do stemming, it return error :
[Error][3]
TypeError Traceback (most recent call
last)
<ipython-input-102-7700a8e3235b> in <module>()
----> 1 df['Message'] = df['Message'].apply(stemmer.stem)
2 df = df[['Message', 'Category']]
3 df.head()
5 frames
/usr/local/lib/python3.7/dist-
packages/Sastrawi/Stemmer/Filter/TextNormalizer.py in
normalize_text(text)
2
3 def normalize_text(text):
----> 4 result = str.lower(text)
5 result = re.sub(r'[^a-z0-9 -]', ' ', result, flags =
re.IGNORECASE|re.MULTILINE)
6 result = re.sub(r'( +)', ' ', result, flags =
re.IGNORECASE|re.MULTILINE)
TypeError: descriptor 'lower' requires a 'str' object but received a
'list'
Hope all you guys can help me

How do I get the image file to be properly labeled when trying to produce topk predictions on an image?

I am trying to produce a graph of the top 5 predictions from a image classifier for any given image. My files are organized as such:
Test/ --> class_name/ --> image_number
for example,
Test/ --> chocolate/ --> 0015254.jpg
When I use the following code, I can't get the class name to redirect to print, it gives an error that results in every class being outputted (shown below).
class_to_idx:
classes = os.listdir(train_folder)
classes.sort()
#print(classes)
label_mapping = {k: v for v, k in enumerate(classes)}
class_to_idx = {classes[i]: i for i in range(len(classes))}
Here is the code to generate an image and print its top5 predictions:
def sanity_check(path):
imagepath = test_folder + path
image = process_image(imagepath)
plot = imshow(image, ax = plt)
plot.axis('off')
plot.title(class_to_idx[str(classes)])
plot.show()
axes = predict(imagepath, model)
yaxis = [class_to_idx[str(i)] for i in np.array(axes[1][0].cpu())]
y_pos = np.arange(len(yaxis))
xaxis = np.array(axes[0][0].cpu().numpy())
plt.barh(y_pos, xaxis)
plt.xlabel('probability')
plt.yticks(y_pos, yaxis)
plt.title('probability of {} classification'.format(name))
plt.show()
path = '/chocolate_mousse/1379570.jpg'
sanity_check(path)
Here is the error:
KeyError Traceback (most recent call last)
<ipython-input-64-5747e27aee19> in <module>()
1 path = '/chocolate_mousse/1379570.jpg'
----> 2 sanity_check(path, name = 'Chocolate Mousse')
<ipython-input-62-295700419574> in sanity_check(path, name)
7 plot = imshow(image, ax = plt)
8 plot.axis('off')
----> 9 plot.title(class_to_idx[str(classes)])
10 plot.show()
11
KeyError: "['apple_pie', 'baby_back_ribs', 'baklava', 'beef_carpaccio', 'beef_tartare', 'beet_salad', 'beignets', .... etc

How to obtain 2D Cutout of an image from a SkyCoord position?

I am following the example from Astropy docs for 2D Cutout.
The header of my FITS file:
SIMPLE = T / file does conform to FITS standard
BITPIX = -32 / number of bits per data pixel
NAXIS = 3 / number of data axes
NAXIS1 = 512 / length of data axis 1
NAXIS2 = 512 / length of data axis 2
NAXIS3 = 3 / length of data axis 3
EXTEND = T / FITS dataset may contain extensions
COMMENT FITS (Flexible Image Transport System) format is defined in 'Astronomy
COMMENT and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H
SURVEY = 'DECaLS '
VERSION = 'DR8-south'
IMAGETYP= 'image '
BANDS = 'grz '
BAND0 = 'g '
BAND1 = 'r '
BAND2 = 'z '
CTYPE1 = 'RA---TAN' / TANgent plane
CTYPE2 = 'DEC--TAN' / TANgent plane
CRVAL1 = 186.11382 / Reference RA
CRVAL2 = 0.15285422 / Reference Dec
CRPIX1 = 256.5 / Reference x
CRPIX2 = 256.5 / Reference y
CD1_1 = -7.27777777777778E-05 / CD matrix
CD1_2 = 0. / CD matrix
CD2_1 = 0. / CD matrix
CD2_2 = 7.27777777777778E-05 / CD matrix
IMAGEW = 512. / Image width
IMAGEH = 512. / Image height
So far what I have tried :
from astropy.coordinates import SkyCoord
from astropy.wcs import WCS
position = SkyCoord(hdu[0].header['CRVAL1']*u.deg,hdu[0].header['CRVAL2']*u.deg)
size = 200*u.pixel
wcs1 = WCS(hdu[0].header)
cutout = Cutout2D(hdu[0].data[0], position ,size, wcs = wcs1 )
I run into error in the last line.
Error :
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-142-7cc21a13e941> in <module>
----> 1 cutout = Cutout2D(hdu[0].data[0], position ,size, wcs = wcs1 )
/Applications/anaconda3/lib/python3.7/site-packages/astropy/nddata/utils.py in __init__(self, data, position, size, wcs, mode, fill_value, copy)
714 if wcs is not None:
715 self.wcs = deepcopy(wcs)
--> 716 self.wcs.wcs.crpix -= self._origin_original_true
717 self.wcs.array_shape = self.data.shape
718 if wcs.sip is not None:
ValueError: operands could not be broadcast together with shapes (3,) (2,) (3,)
My guess is it is because naxis =3 in my file and the documentation assumes naxis = 2. Though I am not sure if that is the actual issue here. Can anybody help fix this error?
Since your WCS is 3d, but you're getting a 2d cutout, you need to drop the 3rd dimension. Try cutout = Cutout2D(hdu[0].data[0], position ,size, wcs = wcs1.celestial ), where .celestial is a convenience tool to drop the third dimension in the WCS.