Population must be a sequence or set. For dicts, use list(d)

2024/10/15 5:20:34

I try to excute this code and I get the error bellow, I get the error in the random function and I don't know how to fix it, please help me.

def load_data(sample_split=0.3, usage='Training', to_cat=True, verbose=True,classes=['Angry','Happy'], filepath='C:/Users/Oussama/Desktop/fer2013.csv'):df = pd.read_csv(filepath)# print df.tail()# print df.Usage.value_counts()df = df[df.Usage == usage]frames = []classes.append('Disgust')for _class in classes:class_df = df[df['emotion'] == emotion[_class]]frames.append(class_df)data = pd.concat(frames, axis=0)rows = random.sample(data.index, int(len(data)*sample_split))data = data.ix[rows]print ('{} set for {}: {}'.format(usage, classes, data.shape))data['pixels'] = data.pixels.apply(lambda x: reconstruct(x))x = np.array([mat for mat in data.pixels]) # (n_samples, img_width, img_height)X_train = x.reshape(-1, 1, x.shape[1], x.shape[2])y_train, new_dict = emotion_count(data.emotion, classes, verbose)print (new_dict)if to_cat:y_train = to_categorical(y_train)return X_train, y_train, new_dict

I get this:

Traceback (most recent call last):File "fer2013datagen.py", line 71, in <module>verbose=True)File "fer2013datagen.py", line 47, in load_datarows = random.sample(data, int(len(data)*sample_split))File"C:\Users\Oussama\AppData\Local\Programs\Python\Python35\lib\random.py",line 311, in sampleraise TypeError("Population must be a sequence or set.  For dicts, uselist(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).
Answer

Your code here:

rows = random.sample(data.index, int(len(data)*sample_split))

But, error message shows

rows = random.sample(data, int(len(data)*sample_split))

Why different? Did you modify it? And what is the type of data is? is it a list? or a dict?

And, error message has already told you how to fix it. it means the first parameter of random.sample must be a sequence or set. For dicts, use list(Dict).

For example,

d = {'a':1,'b':2}
random.sample(list(d), 1)

instead of

random.sample(d, 1)
https://en.xdnf.cn/q/69323.html

Related Q&A

Why do imports fail in setuptools entry_point scripts, but not in python interpreter?

I have the following project structure:project |-project.py |-__init__.py |-setup.py |-lib|-__init__.py|-project|-__init__.py|-tools.pywith project.py:from project.lib import *def main():print("ma…

msgpack unserialising dict key strings to bytes

I am having issues with msgpack in python. It seems that when serialising a dict, if the keys are strings str, they are not unserialised properly and causing KeyError exceptions to be raised.Example:&g…

Better solution for Python Threading.Event semi-busy waiting

Im using pretty standard Threading.Event: Main thread gets to a point where its in a loop that runs:event.wait(60)The other blocks on a request until a reply is available and then initiates a:event.set…

\ufeff Invalid character in identifier

I have the following code :import urllib.requesttry:url = "https://www.google.com/search?q=test"headers = {}usag = Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefo…

Python multiprocessing - Passing a list of dicts to a pool

This question may be a duplicate. However, I read lot of stuff around on this topic, and I didnt find one that matches my case - or at least, I didnt understood it.Sorry for the inconvenance.What Im tr…

Failed to write to file but generates no Error

Im trying to write to a file but its not working. Ive gone through step-by-step with the debugger (it goes to the write command but when I open the file its empty).My question is either: "How do I…

train spacy for text classification

After reading the docs and doing the tutorial I figured Id make a small demo. Turns out my model does not want to train. Heres the codeimport spacy import random import jsonTRAINING_DATA = [["My l…

Python threading vs. multiprocessing in Linux

Based on this question I assumed that creating new process should be almost as fast as creating new thread in Linux. However, little test showed very different result. Heres my code: from multiprocessi…

How to create a visualization for events along a timeline?

Im building a visualization with Python. There Id like to visualize fuel stops and the fuel costs of my car. Furthermore, car washes and their costs should be visualized as well as repairs. The fuel c…

Multiplying Numpy 3D arrays by 1D arrays

I am trying to multiply a 3D array by a 1D array, such that each 2D array along the 3rd (depth: d) dimension is calculated like:1D_array[d]*2D_arrayAnd I end up with an array that looks like, say:[[ [1…