{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":31254,"databundleVersionId":3103714,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 《实验报告4：PySpark大数据预处理》\n---\n### 实验内容：\n1. 使用Spark MLlib进行大数据预处理。\n2. 复习DataFrame的基础操作。\n3. 练习特征工程。\n\n### 实验目标：\n1. 掌握Spark MLlib大数据预处理。\n2. 提高DataFrame的基础操作的熟练度。\n3. 掌握特征工程的基本工具与技术。\n\n### 实验提示:\n\n\n### 实验报告作业提交要求:\n**本次实验为个人作业，计时练习，请在下课前提交.word答题纸和.ipynb文件**","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"\n\nH&M集团拥有53个在线市场和4850家商店。H&M在线商店为购物者提供了广泛的产品选择以供浏览。但是，由于选择太多，顾客可能无法迅速找到他们感兴趣的产品或他们正在寻找的产品，最终，他们可能不会进行购买。为了增强购物体验，产品推荐至关重要。更重要的是，帮助顾客做出正确的选择对可持续性也有积极的影响，因为它减少了退货，从而最小化了运输排放。\n\nH&M集团邀请你基于以往的交易数据以及客户和产品元数据来开发产品推荐系统。可用的元数据包括简单的数据，如服装类型和顾客年龄，产品描述的文本数据，以及服装图像的图像数据。\n\n数据集中哪些信息可能有用需要你来发现和决定。如果你想研究分类数据类型的算法，或者深入研究自然语言处理和图像处理的深度学习，这都取决于你。\n\n**在实验报告四中，我们使用Kaggle笔记本对H&M集团的销售信息进行探索性分析和简单的预处理。所需数据在笔记本Input栏中的。请在《实验报告纸》 中回答以下问题。每个问题1分。**","metadata":{}},{"cell_type":"code","source":"# Install pyspark\n!pip install pyspark\n# Create a spark session\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder.master('local[*]').appName('HW4').getOrCreate()\n# Import spark sql functions\nfrom pyspark.sql.functions import *","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:26:02.072196Z","iopub.execute_input":"2024-11-01T16:26:02.072614Z","iopub.status.idle":"2024-11-01T16:26:22.704678Z","shell.execute_reply.started":"2024-11-01T16:26:02.072576Z","shell.execute_reply":"2024-11-01T16:26:22.703216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## A 交易数据\n","metadata":{}},{"cell_type":"markdown","source":"**<span> Transactions data description: </span>**\n\n> `t_dat` **<span style=\"color:#023e8a;\">: A unique identifier of every customer</span>**  \n> `customer_id` **<span style=\"color:#023e8a;\">: A unique identifier of every customer </span>**  **<span style=\"color:#FF0000;\">(in </span>** `customers` **<span style=\"color:#FF0000;\"> table)</span>**  \n> `article_id` **<span style=\"color:#023e8a;\">: A unique identifier of every article</span>**  **<span style=\"color:#FF0000;\">(in </span>** `articles` **<span style=\"color:#FF0000;\"> table)</span>**  \n> `price` **<span style=\"color:#023e8a;\">: Price of purchase</span>**  \n> `sales_channel_id` **<span style=\"color:#023e8a;\">: 1 or 2</span>**  ","metadata":{"execution":{"iopub.status.busy":"2024-11-01T13:34:55.038397Z","iopub.execute_input":"2024-11-01T13:34:55.039911Z","iopub.status.idle":"2024-11-01T13:34:55.052933Z","shell.execute_reply.started":"2024-11-01T13:34:55.039858Z","shell.execute_reply":"2024-11-01T13:34:55.051232Z"}}},{"cell_type":"markdown","source":"读取transactions_train.csv数据，生成DataFrame transaction，回答：\n* 1.transaction有多少列？(      )\n* 2.transaction有多少行？(      )\n* 3.transaction第0列的名称和类型是什么？(      )","metadata":{}},{"cell_type":"code","source":"# 读取数据\ntransaction = spark.read.format('csv').option(\"header\",True) \\\n              .load(\"../input/h-and-m-personalized-fashion-recommendations/transactions_train.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:26:22.707320Z","iopub.execute_input":"2024-11-01T16:26:22.708044Z","iopub.status.idle":"2024-11-01T16:26:30.692995Z","shell.execute_reply.started":"2024-11-01T16:26:22.707993Z","shell.execute_reply":"2024-11-01T16:26:30.691653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transaction.printSchema()\ntransaction.count()","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:26:30.694643Z","iopub.execute_input":"2024-11-01T16:26:30.695159Z","iopub.status.idle":"2024-11-01T16:26:40.546898Z","shell.execute_reply.started":"2024-11-01T16:26:30.695104Z","shell.execute_reply":"2024-11-01T16:26:40.545251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"从transaction中按照0.5%的比例，随机抽取一个样本，将随机种子设置为123456，命名为df，回答：\n* 4.df第一行的article_id是多少？(         )","metadata":{}},{"cell_type":"code","source":"#随机抽样\ndf = transaction.sample(0.005,123456) #用于随机抽样的函数\ndf.show(1)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:26:40.551174Z","iopub.execute_input":"2024-11-01T16:26:40.551748Z","iopub.status.idle":"2024-11-01T16:26:41.002905Z","shell.execute_reply.started":"2024-11-01T16:26:40.551690Z","shell.execute_reply":"2024-11-01T16:26:41.001227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"使用df，计算并回答：\n* 5.数据中包含多少个不同的消费者？（）\n* 6.购买商品总数最多的第五名消费者的购买商品总数是什么？（） \n* 7.购买总额最大的第五名消费者的购买总额是多少？（）","metadata":{}},{"cell_type":"code","source":"df.select(count_distinct('customer_id')).show()","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:26:41.005154Z","iopub.execute_input":"2024-11-01T16:26:41.005672Z","iopub.status.idle":"2024-11-01T16:27:04.128508Z","shell.execute_reply.started":"2024-11-01T16:26:41.005620Z","shell.execute_reply":"2024-11-01T16:27:04.127240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.groupBy('customer_id')\\\n.agg(count('article_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:27:04.129887Z","iopub.execute_input":"2024-11-01T16:27:04.130356Z","iopub.status.idle":"2024-11-01T16:27:28.296567Z","shell.execute_reply.started":"2024-11-01T16:27:04.130306Z","shell.execute_reply":"2024-11-01T16:27:28.295383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.groupBy('customer_id')\\\n.agg(sum('price')\\\n.alias('sum')).sort('sum', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:27:28.298029Z","iopub.execute_input":"2024-11-01T16:27:28.298509Z","iopub.status.idle":"2024-11-01T16:27:51.680181Z","shell.execute_reply.started":"2024-11-01T16:27:28.298459Z","shell.execute_reply":"2024-11-01T16:27:51.678983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"将交易时间列从string类型转换为date类型，生成dfDate，回答：\n* 8.交易最多的年份是哪一年？（）\n* 9.交易最多的月份是哪个月？（）\n* 10.周几的交易最多？（）","metadata":{}},{"cell_type":"code","source":"dfDate = df.withColumn('date',to_date('t_dat'))\\\n.withColumn('year',year('date'))\\\n.withColumn('month',month('date'))\\\n.withColumn('dayofweek',dayofweek('date'))\ndfDate.show(1)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:27:51.681576Z","iopub.execute_input":"2024-11-01T16:27:51.682099Z","iopub.status.idle":"2024-11-01T16:27:52.028954Z","shell.execute_reply.started":"2024-11-01T16:27:51.682048Z","shell.execute_reply":"2024-11-01T16:27:52.027765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dfDate.groupBy('year')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:27:52.030665Z","iopub.execute_input":"2024-11-01T16:27:52.031167Z","iopub.status.idle":"2024-11-01T16:28:14.564372Z","shell.execute_reply.started":"2024-11-01T16:27:52.031115Z","shell.execute_reply":"2024-11-01T16:28:14.563084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dfDate.groupBy('month')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:28:14.569526Z","iopub.execute_input":"2024-11-01T16:28:14.570113Z","iopub.status.idle":"2024-11-01T16:28:37.000609Z","shell.execute_reply.started":"2024-11-01T16:28:14.570041Z","shell.execute_reply":"2024-11-01T16:28:36.999200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dfDate.groupBy('dayofweek')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:28:37.002138Z","iopub.execute_input":"2024-11-01T16:28:37.002779Z","iopub.status.idle":"2024-11-01T16:28:59.232636Z","shell.execute_reply.started":"2024-11-01T16:28:37.002723Z","shell.execute_reply":"2024-11-01T16:28:59.230947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## B 商品数据\n读取articles.csv，将随机种子设置为**你的学号**，从中抽取50%的样本，命名为df2回答：\n* 11.df2第一行记录的articles_id是什么？（）\n\n使用inner join，将df2连接到dfDate上，生成df3，回答：\n* 12. df3有多少行？()\n* 13. 交易数量最多的商品大类（department_name）是什么？（）\n* 14. 交易数量最多的商品类别（product_type_name）是什么？（）\n* 15. 交易数量最多的商品颜色（colour_group_name）是什么？（）\n","metadata":{}},{"cell_type":"code","source":"# 读取数据\narticle = spark.read.format('csv').option(\"header\",True) \\\n              .load(\"/kaggle/input/h-and-m-personalized-fashion-recommendations/articles.csv\")\narticle.printSchema()\narticle.count()","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:28:59.234440Z","iopub.execute_input":"2024-11-01T16:28:59.235096Z","iopub.status.idle":"2024-11-01T16:28:59.928033Z","shell.execute_reply.started":"2024-11-01T16:28:59.235032Z","shell.execute_reply":"2024-11-01T16:28:59.926830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df2 = article.sample(0.5,123456)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:28:59.929235Z","iopub.execute_input":"2024-11-01T16:28:59.930305Z","iopub.status.idle":"2024-11-01T16:28:59.943464Z","shell.execute_reply.started":"2024-11-01T16:28:59.930245Z","shell.execute_reply":"2024-11-01T16:28:59.940918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df2.show(1)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:28:59.945828Z","iopub.execute_input":"2024-11-01T16:28:59.946598Z","iopub.status.idle":"2024-11-01T16:29:00.204180Z","shell.execute_reply.started":"2024-11-01T16:28:59.946540Z","shell.execute_reply":"2024-11-01T16:29:00.202578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df3 = dfDate.join(df2,'article_id','inner')","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:29:00.205623Z","iopub.execute_input":"2024-11-01T16:29:00.206142Z","iopub.status.idle":"2024-11-01T16:29:00.273744Z","shell.execute_reply.started":"2024-11-01T16:29:00.206089Z","shell.execute_reply":"2024-11-01T16:29:00.272502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df3.count()","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:29:00.275142Z","iopub.execute_input":"2024-11-01T16:29:00.275623Z","iopub.status.idle":"2024-11-01T16:29:24.415325Z","shell.execute_reply.started":"2024-11-01T16:29:00.275572Z","shell.execute_reply":"2024-11-01T16:29:24.413875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df3.groupBy('department_name')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:29:24.417409Z","iopub.execute_input":"2024-11-01T16:29:24.417924Z","iopub.status.idle":"2024-11-01T16:29:50.941325Z","shell.execute_reply.started":"2024-11-01T16:29:24.417869Z","shell.execute_reply":"2024-11-01T16:29:50.939949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df3.groupBy('product_type_name')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:29:50.942879Z","iopub.execute_input":"2024-11-01T16:29:50.944058Z","iopub.status.idle":"2024-11-01T16:30:17.362374Z","shell.execute_reply.started":"2024-11-01T16:29:50.943986Z","shell.execute_reply":"2024-11-01T16:30:17.360943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df3.groupBy('colour_group_name')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:30:17.364051Z","iopub.execute_input":"2024-11-01T16:30:17.364568Z","iopub.status.idle":"2024-11-01T16:30:42.311301Z","shell.execute_reply.started":"2024-11-01T16:30:17.364510Z","shell.execute_reply":"2024-11-01T16:30:42.310020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## C 用户数据\n","metadata":{}},{"cell_type":"markdown","source":"读取customers.csv，命名为df4. 使用inner join，将df4连接到df3上，生成df5，回答：\n* 16. df5有多少行？()\n* 17. 将用户年龄age按百分数分为5组，生成df6, df6中交易数量最多的用户年龄组是什么？（）\n* 18. df6中交易数量最多的用户时尚信息关注程度fashion_news_frequency是什么？（）\n\n","metadata":{}},{"cell_type":"code","source":"# 读取数据\ncustomer = spark.read.format('csv').option(\"header\",True) \\\n              .load(\"/kaggle/input/h-and-m-personalized-fashion-recommendations/customers.csv\")\ncustomer.printSchema()\ncustomer.count()","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:30:42.313126Z","iopub.execute_input":"2024-11-01T16:30:42.313505Z","iopub.status.idle":"2024-11-01T16:30:43.095738Z","shell.execute_reply.started":"2024-11-01T16:30:42.313468Z","shell.execute_reply":"2024-11-01T16:30:43.094329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df5 = df3.join(customer,'customer_id','inner').withColumn('age',col('age').cast('int'))\ndf5.count()","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:30:43.097582Z","iopub.execute_input":"2024-11-01T16:30:43.098127Z","iopub.status.idle":"2024-11-01T16:31:14.736759Z","shell.execute_reply.started":"2024-11-01T16:30:43.098086Z","shell.execute_reply":"2024-11-01T16:31:14.734619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# QuantileDiscretizer\nfrom pyspark.ml.feature import QuantileDiscretizer\nbucketer = QuantileDiscretizer().setNumBuckets(5).setInputCol('age').setOutputCol(\"age_group\")\nfittedBucketer = bucketer.fit(df5)\ndf6 = fittedBucketer.transform(df5)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:31:14.738636Z","iopub.execute_input":"2024-11-01T16:31:14.739238Z","iopub.status.idle":"2024-11-01T16:31:46.573694Z","shell.execute_reply.started":"2024-11-01T16:31:14.739179Z","shell.execute_reply":"2024-11-01T16:31:46.572117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df6.groupBy('age_group')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)\n\ndf6.groupBy('fashion_news_frequency')\\\n.agg(count('customer_id')\\\n.alias('count')).sort('count', ascending=False).show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:31:46.575729Z","iopub.execute_input":"2024-11-01T16:31:46.576573Z","iopub.status.idle":"2024-11-01T16:32:48.780422Z","shell.execute_reply.started":"2024-11-01T16:31:46.576509Z","shell.execute_reply":"2024-11-01T16:32:48.778925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## D 特征工程\n在df6的基础上，将以下列组合成一个数值向量特征，组合之前需要对相应的列进行处理，转换成数值列。\n\n* day-of-week\n* price\n* colour_group_name\n* age\n* fashion_news_frequency\n\n回答\n* 19.最后生成的特征向量有多少个元素？（）\n* 20.解释第一行的特征向量的含义。（）\n\n\n","metadata":{}},{"cell_type":"code","source":"# 1 SQLTransformer\nfrom pyspark.ml.feature import SQLTransformer\n\nsqlT = SQLTransformer()\\\n  .setStatement(\"\"\"\n  SELECT\n  month,\n  CAST(price as DOUBLE),\n  colour_group_name,\n  CAST(age as INT),\n  fashion_news_frequency\n  FROM __THIS__\n  \"\"\")\n\n# 2 QuantileDiscretizer\nfrom pyspark.ml.feature import QuantileDiscretizer\nqD = QuantileDiscretizer().setNumBuckets(5).setInputCol('age').setOutputCol('ageI')\n\n# 3 StringIndexer\nfrom pyspark.ml.feature import StringIndexer\n# 4 OneHotEncoder\nfrom pyspark.ml.feature import OneHotEncoder\nsI1 = StringIndexer().setInputCol(\"month\").setOutputCol(\"month1\")\nohE1= OneHotEncoder().setInputCol(\"month1\").setOutputCol(\"month2\")\n\nsI2 = StringIndexer().setInputCol(\"colour_group_name\").setOutputCol(\"colour_group_name1\")\nohE2= OneHotEncoder().setInputCol(\"colour_group_name1\").setOutputCol(\"colour_group_name2\")\n\nsI3 = StringIndexer().setInputCol(\"fashion_news_frequency\").setOutputCol(\"fashion_news_frequency1\")\nohE3 = OneHotEncoder().setInputCol(\"fashion_news_frequency1\").setOutputCol(\"fashion_news_frequency2\")\n\n# 5 VectorAssembler\nfrom pyspark.ml.feature import VectorAssembler\nvA = VectorAssembler(handleInvalid = 'skip' )\\\n.setInputCols(['month2','price','colour_group_name2','ageI'\n,'fashion_news_frequency2'])\\\n.setOutputCol('features')\n\n# 创建 Pipeline\nfrom pyspark.ml.pipeline import Pipeline\npipeline = Pipeline(stages=[sqlT,qD, sI1,ohE1, sI2,ohE2,\n                           sI3,ohE3,vA])\n\n# 拟合数据并转换\nmodel = pipeline.fit(df6)\ndf7 = model.transform(df6)\n\n# 查看结果\ndf7.show(5, False)","metadata":{"execution":{"iopub.status.busy":"2024-11-01T16:32:48.781760Z","iopub.execute_input":"2024-11-01T16:32:48.782282Z","iopub.status.idle":"2024-11-01T16:35:29.959609Z","shell.execute_reply.started":"2024-11-01T16:32:48.782221Z","shell.execute_reply":"2024-11-01T16:35:29.957562Z"},"trusted":true},"execution_count":null,"outputs":[]}]}