如何正确使用dask.delayed

如何解决如何正确使用dask.delayed

我做了一个计时实验,但我不认为自己在正确使用dask.delayed。这是代码:

import pandas as pd
import dask
import time

def my_operation(row_str: str):
    text_to_add = 'Five Michigan State University students—Ash Williams,his girlfriend,Linda; his sister,Cheryl; their friend Scott; and Scotts girlfriend Shelly—vacation at an isolated cabin in rural Tennessee. Approaching the cabin,the group notices the porch swing move on its own but suddenly stop as Scott grabs the doorknob. While Cheryl draws a picture of a clock,the clock stops,and she hears a faint,demonic voice tell her to "join us". Her hand becomes possessed,turns pale and draws a picture of a book with a demonic face on its cover. Although shaken,she does not mention the incident.'
    new_str = row_str + ' ' + text_to_add
    return new_str

def gen_sequential(n_rows: int):
    df = pd.read_csv('path/to/myfile.csv',nrows=n_rows)
    results_list = []
    tic = time.perf_counter()
    for ii in range(df.shape[0]):
        my_new_str = my_operation(df.iloc[ii,0])
        results_list.append(my_new_str)
    toc = time.perf_counter()
    task_time = toc - tic
    return results_list,task_time

def gen_pandas_apply(n_rows: int):
    df = pd.read_csv('path/to/myfile.csv',nrows=n_rows)
    tic = time.perf_counter()
    df['gen'] = df['text'].apply(my_operation)
    toc = time.perf_counter()
    task_time = toc - tic
    return df,task_time

def gen_dask_compute(n_rows: int):
    df = pd.read_csv('path/to/myfile.csv',nrows=n_rows)
    results_list = []
    tic = time.perf_counter()
    for ii in range(df.shape[0]):
        my_new_str = dask.delayed(my_operation)(df.iloc[ii,0])
        results_list.append(my_new_str)

    results_list = dask.compute(*results_list)
    toc = time.perf_counter()
    task_time = toc-tic
    return results_list,task_time

n_rows = 16
times = []
for ii in range(100):
    #_,t_dask_task = gen_sequential(n_rows)
    #_,t_dask_task = gen_pandas_apply(n_rows)
    _,t_dask_task = gen_dask_compute(n_rows)
    times.append(t_dask_task)
t_mean = sum(times)/len(times)
print('average time for 100 iterations: {}'.format(t_mean))

我对文件中的8、64、256、1024、32768、262144和1048576行(​​仅约200万行文本)进行了测试,并将其与gen_sequential()和{{1 }}。结果如下:

gen_pandas_apply()

我认为我没有正确使用n_rows sequential[s] pandas_apply[s] dask_compute[s] =========================================================================== 8 0.000288928459959 0.001460871489944 0.002077747459807 --------------------------------------------------------------------------- 64 0.001723313619877 0.001805401749916 0.011105699519758 --------------------------------------------------------------------------- 256 0.006383508619801 0.00198456062968 0.046899785500136 --------------------------------------------------------------------------- 1024 0.022589521310038 0.002799118410258 0.197301750000333 --------------------------------------------------------------------------- 32768 0.63460024946984 0.035047864249209 5.91377260136054 --------------------------------------------------------------------------- 262144 5.28406698709983 0.254192861450574 50.5853837806704 --------------------------------------------------------------------------- 1048576 21.1142608421401 0.967728560800169 195.71797474096 --------------------------------------------------------------------------- ,因为较大的dask.delayed的平均计算时间比其他方法要长。我希望n_rows的最大优势随着数据集的增加而变得明显。有谁知道我要去哪里错了?这是我的设置:

  • python:3.7.6
  • 任务:2.11.0
  • 熊猫:1.0.5
  • OS:Pop_OS! 20.04 LTS
  • 具有3个内核和32GB内存的虚拟机

我目前正在阅读dask.delayed,但是目前我只限于在该项目中使用Vaex。预先感谢您的帮助!

解决方法

my_operation运行所花费的时间每行很小。即使使用“线程”调度程序,Dask也会增加每个任务的开销,而python的GIL确实意味着这样的非矢量化操作实际上不能并行运行。

就像您应该避免迭代pandas数据框一样,您也应该真正避免对其进行迭代,并分派每一行以便dask进行处理。

您知道Dask具有类似熊猫的数据框API吗? 您可以这样做:

import dask.dataframe as dd
df = dd.read_csv('path/to/myfile.csv')
out = df['text'].map(my_operation)

但是请记住:熊猫既快速又高效,因此对于适合内存的事物,将Dask分为多个工作块通常不会更快,特别是当您输出与输入一样大的数据(而不是聚合)时。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res