Nagy fájl párhuzamos feldolgozása Pythonban

Nagy fájl párhuzamos feldolgozása Pythonban

Forrás csomópont: 1970104

Nagy fájl párhuzamos feldolgozása Pythonban
A kép szerzője
 

For parallel processing, we divide our task into sub-units. It increases the number of jobs processed by the program and reduces overall processing time. 

For example, if you are working with a large CSV file and you want to modify a single column. We will feed the data as an array to the function, and it will parallel process multiple values at once based on the number of available  dolgozók. These workers are based on the number of cores within your processor. 
 

Jegyzet: using parallel processing on a smaller dataset will not improve processing time.

 

In this blog, we will learn how to reduce processing time on large files using több feldolgozás, joblibés tqdm Python packages. It is a simple tutorial that can apply to any file, database, image, video, and audio. 
 

Jegyzet: we are using the Kaggle notebook for the experiments. The processing time can vary from machine to machine.  

 

Használni fogjuk a US Accidents (2016 – 2021) dataset from Kaggle which consists of 2.8 million records and 47 columns. 

importálni fogunk multiprocessing, joblibés tqdm mert párhuzamos feldolgozás, pandas mert data ingestionsés re, nltkés string mert szövegfeldolgozás

# Parallel Computing
importál több feldolgozás as mp
ból ből joblib importál Parallel, delayed
ból ből tqdm.notebook importál tqdm # Data Ingestion 
importál pandák as pd # Text Processing 
importál re ból ből nltk.corpus importál stopszavak
importál húr

Before we jump right in, let’s set n_workers by doubling cpu_count(). As you can see, we have 8 workers.

n_workers = 2 * mp.cpu_count() print(f"{n_workers} workers are available") >>> 8 workers are available

In the next step, we will ingest large CSV files using the pandák read_csv function. Then, print out the shape of the dataframe, the name of the columns, and the processing time. 

Jegyzet: Jupyter’s magic function %%time képes megjeleníteni CPU times és a fali idő at the end of the process. 

 

%%time
file_name="../input/us-accidents/US_Accidents_Dec21_updated.csv"
df = pd.read_csv(file_name) print(f"Shape:{df.shape}nnColumn Names:n{df.columns}n")

teljesítmény

Shape:(2845342, 47) Column Names: Index(['ID', 'Severity', 'Start_Time', 'End_Time', 'Start_Lat', 'Start_Lng', 'End_Lat', 'End_Lng', 'Distance(mi)', 'Description', 'Number', 'Street', 'Side', 'City', 'County', 'State', 'Zipcode', 'Country', 'Timezone', 'Airport_Code', 'Weather_Timestamp', 'Temperature(F)', 'Wind_Chill(F)', 'Humidity(%)', 'Pressure(in)', 'Visibility(mi)', 'Wind_Direction', 'Wind_Speed(mph)', 'Precipitation(in)', 'Weather_Condition', 'Amenity', 'Bump', 'Crossing', 'Give_Way', 'Junction', 'No_Exit', 'Railway', 'Roundabout', 'Station', 'Stop', 'Traffic_Calming', 'Traffic_Signal', 'Turning_Loop', 'Sunrise_Sunset', 'Civil_Twilight', 'Nautical_Twilight', 'Astronomical_Twilight'],
dtype='object') CPU times: user 33.9 s, sys: 3.93 s, total: 37.9 s
Wall time: 46.9 s

A clean_text is a straightforward function for processing and cleaning the text. We will get English stopszavak segítségével nltk.copus the use it to filter out stop words from the text line. After that, we will remove special characters and extra spaces from the sentence. It will be the baseline function to determine processing time for sorozatszám, párhuzamosés batch feldolgozás. 

def tiszta_szöveg(text): # Remove stop words stops = stopwords.words("english") text = " ".join([word mert szó in text.split() if szó nem in stops]) # Remove Special Characters text = text.translate(str.maketrans('', '', string.punctuation)) # removing the extra spaces text = re.sub(' +',' ', text) visszatérés szöveg

For serial processing, we can use the pandas .apply() function, but if you want to see the progress bar, you need to activate tqdm mert pandák majd használja a .progress_apply() funkciót. 

We are going to process the 2.8 million records and save the result back to the “Description” column column. 

%%time
tqdm.pandas() df['Description'] = df['Description'].progress_apply(clean_text)

teljesítmény

It took 9 minutes and 5 seconds for the high-end processor to serial process 2.8 million rows. 

100% 2845342/2845342 [09:05<00:00, 5724.25it/s] CPU times: user 8min 14s, sys: 53.6 s, total: 9min 7s
Wall time: 9min 5s

There are various ways to parallel process the file, and we are going to learn about all of them. The multiprocessing is a built-in python package that is commonly used for parallel processing large files. 

We will create a multiprocessing Medence karbantartására val vel 8 dolgozók és használja a térkép function to initiate the process. To display progress bars, we are using tqdm.

The map function consists of two sections. The first requires the function, and the second requires an argument or list of arguments. 

Learn more by reading dokumentáció

%%time
p = mp.Pool(n_workers) df['Description'] = p.map(clean_text,tqdm(df['Description']))

teljesítmény

We have improved our processing time by almost 3X. The processing time dropped from 9 perc 5 másodperc nak nek 3 perc 51 másodperc.   

100% 2845342/2845342 [02:58<00:00, 135646.12it/s] CPU times: user 5.68 s, sys: 1.56 s, total: 7.23 s
Wall time: 3min 51s

We will now learn about another Python package to perform parallel processing. In this section, we will use joblib’s Párhuzamos és a késleltetett to replicate the térkép funkciót. 

  • The Parallel requires two arguments: n_jobs = 8 and backend = multiprocessing.
  • Then, we will add tiszta_szöveg  hoz késleltetett funkciót. 
  • Create a loop to feed a single value at a time. 

The process below is quite generic, and you can modify your function and array according to your needs. I have used it to process thousands of audio and video files without any issue. 

Ajánlott: add exception handling using try: és a except:

def text_parallel_clean(array): result = Parallel(n_jobs=n_workers,backend="multiprocessing")( delayed(clean_text) (text) mert szöveg in tqdm(array) ) visszatérés eredményez

Add the “Description” column to text_parallel_clean()

%%time
df['Description'] = text_parallel_clean(df['Description'])

teljesítmény

It took our function 13 seconds more than multiprocessing the Medence. Még akkor is, Párhuzamos is 4 minutes and 59 seconds faster than sorozatszám feldolgozás. 

100% 2845342/2845342 [04:03<00:00, 10514.98it/s] CPU times: user 44.2 s, sys: 2.92 s, total: 47.1 s
Wall time: 4min 4s

There is a better way to process large files by splitting them into batches and processing them parallel. Let’s start by creating a batch function that will run a clean_function on a single batch of values. 

Batch Processing Function

def proc_batch(batch): visszatérés [ clean_text(text) mert szöveg in batch ]

Splitting the File into Batches

The function below will split the file into multiple batches based on the number of workers. In our case, we get 8 batches. 

def batch_file(array,n_workers): file_len = len(array) batch_size = round(file_len / n_workers) batches = [ array[ix:ix+batch_size] mert ix in tqdm(range(0, file_len, batch_size)) ] visszatérés batches batches = batch_file(df['Description'],n_workers) >>> 100% 8/8 [00:00<00:00, 280.01it/s]

Running Parallel Batch Processing

Finally, we will use Párhuzamos és a késleltetett to process batches. 

Jegyzet: To get a single array of values, we have to run list comprehension as shown below. 

 

%%time
batch_output = Parallel(n_jobs=n_workers,backend="multiprocessing")( delayed(proc_batch) (batch) mert batch in tqdm(batches) ) df['Description'] = [j mert i in batch_output mert j in i]

teljesítmény

We have improved the processing time. This technique is famous for processing complex data and training deep learning models. 

100% 8/8 [00:00<00:00, 2.19it/s] CPU times: user 3.39 s, sys: 1.42 s, total: 4.81 s
Wall time: 3min 56s

tqdm takes multiprocessing to the next level. It is simple and powerful. I will recommend it to every data scientist. 

Nézze meg a dokumentáció to learn more about multiprocessing. 

A process_map igényel:

  1. Funkció neve
  2. Dataframe column
  3. max_workers
  4. chucksize is similar to batch size. We will calculate the batch size using the number of workers or you can add the number based on your preference. 
%%idő
ból ből tqdm.contrib.concurrent importál process_map
batch = round(len(df)/n_workers) df["Description"] = process_map( clean_text, df["Description"], max_workers=n_workers, chunksize=batch
)

teljesítmény

With a single line of code, we get the best result. 

100% 2845342/2845342 [03:48<00:00, 1426320.93it/s] CPU times: user 7.32 s, sys: 1.97 s, total: 9.29 s
Wall time: 3min 51s

You need to find a balance and select the technique that works best for your case. It can be serial processing, parallel, or batch processing. The parallel processing can backfire if you are working with a smaller, less complex dataset. 

In this mini-tutorial, we have learned about various Python packages and techniques that allow us to parallel process our data functions. 

If you are only working with a tabular dataset and want to improve your processing performance, then I will suggest you try Irányítópult, adattáblaés ZUHATAG 

Referencia 

 
 
Abid Ali Awan (@1abidaliawan) okleveles adattudós szakember, aki szereti a gépi tanulási modellek építését. Jelenleg tartalomkészítéssel foglalkozik, és technikai blogokat ír a gépi tanulásról és az adattudományi technológiákról. Abid mesterdiplomát szerzett technológiamenedzsmentből és alapdiplomát távközlési mérnökből. Elképzelése az, hogy egy MI-terméket hozzon létre egy gráf neurális hálózat segítségével a mentális betegséggel küzdő diákok számára.
 

Időbélyeg:

Még több KDnuggets