举荐:应用NSDT场景编辑器助你疾速搭建可编辑的3D利用场景
简略的数据处理脚本
我认为一个好的终点是某种数据处理脚本。因为我打算让 ChatGPT 之后应用各种 Python 库编写一些机器学习脚本,这仿佛是一个正当的终点。
指标
首先,我想尝试加载数据集;确保所有数据集值都是数值,或将其转换为数值;查看缺失值;并将数据集拆分为训练集和测试集。
提醒
编写一个 Python 脚本来执行以下操作:
- 将数据集从磁盘上的 csv 加载到 Pandas 数据帧-
- 确保数据集齐全是数字;
- 将字符串值转换为数字,并在字典中跟踪此转换以供当前援用 - 检查数据帧中的缺失值,并为具备一个缺失值的任何记录插补缺失值;齐全删除具备多个缺失值的记录 - 将数据集拆分为测试和训练集
回应
- import pandas as pd# Load dataset from csv to DataFramedf = pd.read_csv('dataset.csv')# Initialize dictionary to track string to numeric conversionsconversions = {}# Convert string values to numeric and track conversions in dictionaryfor col in df.columns: if df[col].dtype == object: conversions[col] = {val: i for i, val in enumerate(df[col].unique())} df[col] = df[col].map(conversions[col])# Check for missing valuesmissing_values = df.isna().sum()# Impute missing values for records with one missing valuefor col in missing_values[missing_values == 1].index: df[col].fillna(df[col].median(), inplace=True)# Drop records with more than one missing valuedf.dropna(thresh=len(df.columns) - 1, inplace=True)# Split dataset into test and training setsfrom sklearn.model_selection import train_test_splittrain_df, test_df = train_test_split(df, test_size=0.2)
留神:脚本从csv文件名“dataset.csv”加载数据集,并将数据帧拆分为80/20比率的测试和训练集。如果要应用不同的文件名或比率,请相应地更改门路/比率。
剖析之情
ChatGPT生成了一个有用的脚本。它决定了数据集名称以及训练/测试拆分百分比,并记录了这两个点以及如何依据须要更改它们。总的来说,工作实现了。
重构咱们的代码
指标
当初咱们有一个能够执行某些操作的脚本,让咱们略微重构一下。良好编码的基石是应用函数来逻辑地组织代码,促成重用,并确保您不会反复本人。
提醒
重写下面的脚本以应用一系列有意义的函数
回应
import pandas as pdfrom sklearn.model_selection import train_test_splitdef load_and_convert_data(file_path): # Load dataset from csv to DataFrame df = pd.read_csv(file_path) # Initialize dictionary to track string to numeric conversions conversions = {} # Convert string values to numeric and track conversions in dictionary for col in df.columns: if df[col].dtype == object: conversions[col] = {val: i for i, val in enumerate(df[col].unique())} df[col] = df[col].map(conversions[col]) return df, conversionsdef handle_missing_values(df): # Check for missing values missing_values = df.isna().sum() # Impute missing values for records with one missing value for col in missing_values[missing_values == 1].index: df[col].fillna(df[col].median(), inplace=True) # Drop records with more than one missing value df.dropna(thresh=len(df.columns) - 1, inplace=True) return dfdef split_data(df, test_size): return train_test_split(df, test_size=test_size)# Use the functionsfile_path = "dataset.csv"df, conversions = load_and_convert_data(file_path)df = handle_missing_values(df)train_df, test_df = split_data(df, 0.2)
在这里,我应用了三个函数:
- load_and_convert_data(file_path) 加载 CSV 数据集并将字符串值转换为数字。
- handle_missing_values(df) 解决数据集中的缺失值。
- split_data(df,test_size)将数据集拆分为测试和训练集。
主脚本应用这些函数来加载、转换和清理数据集,而后将其拆分为测试和训练集。数据集的门路和测试比率是这些函数的输出。
剖析之情
如果你看一下 ChatGPT 输入的第一个脚本,你可能会看到一些相当显著的线条,你会画出哪些性能将被分成函数。我当然做到了。在这方面,ChatGPT 齐全依照我的预期做了。同样,曾经生成了一个称职的脚本。
扩大咱们的代码
指标
好的,咱们的脚本当初看起来好一点,因为它应用了一些函数进行组织。接下来,让咱们略微扩大脚本,以便用户能够在运行脚本时指定一些参数。
提醒
重写上述程序,以参数的模式从命令行申请以下内容,并在程序中应用它们:- 数据集 CSV 文件的门路/名称 - 训练/测试拆分大小- 每条记录要抛弃的缺失值数的阈值,之后删除整个记录,而不是插补缺失值
回应
import pandas as pdimport argparsefrom sklearn.model_selection import train_test_splitdef load_and_convert_data(file_path): # Load dataset from csv to DataFrame df = pd.read_csv(file_path) # Initialize dictionary to track string to numeric conversions conversions = {} # Convert string values to numeric and track conversions in dictionary for col in df.columns: if df[col].dtype == object: conversions[col] = {val: i for i, val in enumerate(df[col].unique())} df[col] = df[col].map(conversions[col]) return df, conversionsdef handle_missing_values(df, threshold): # Check for missing values missing_values = df.isna().sum() # Impute missing values for records with one missing value for col in missing_values[missing_values == 1].index: df[col].fillna(df[col].median(), inplace=True) # Drop records with more than threshold missing value df.dropna(thresh=len(df.columns) - threshold, inplace=True) return dfdef split_data(df, test_size): return train_test_split(df, test_size=test_size)if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("file_path", help="path/name of the dataset csv file") parser.add_argument("test_size", help="train/test split size", type=float) parser.add_argument("threshold", help="threshold for the number of missing values per record", type=int) args = parser.parse_args() # Use the functions df, conversions = load_and_convert_data(args.file_path) df = handle_missing_values(df, args.threshold) train_df, test_df = split_data(df, args.test_size)
在此版本中,我应用 argparse 模块将文件门路、测试/训练拆分大小和每条记录缺失值数的阈值的输出作为命令行参数。用户必须应用正确的参数运行脚本,例如:python script.py dataset.csv 0.2 1
这将应用“dataset.csv”文件运行脚本,test_size为 0.2,缺失值的阈值为 1。
主脚本在函数中应用这些参数来加载、转换和清理数据集,而后将其拆分为测试和训练集。还值得一提的是,运行脚本时,应从命令行运行脚本,而不是从 IDE 运行脚本。
剖析之情
诚实说,这里不须要太多剖析,因为 ChatGPT 解释了它做得很好的中央。我实际上会在这里留神到一些我以前没有的货色,并拍拍 ChatGPT 的后背,因为它的评论富裕表现力和简洁。
将咱们的代码转换为流光应用程序
指标
当初,假如咱们想使这段代码“生产”准备就绪(风趣我)。让咱们让 ChatGPT 将这些性能包装在 Streamlit 应用程序中。
提醒
将上述程序重写为 Streamlit 应用程序,容许用户提供与上述命令行参数雷同的参数
回应
import pandas as pdimport streamlit as stfrom sklearn.model_selection import train_test_splitdef load_and_convert_data(file_path): # Load dataset from csv to DataFrame df = pd.read_csv(file_path) # Initialize dictionary to track string to numeric conversions conversions = {} # Convert string values to numeric and track conversions in dictionary for col in df.columns: if df[col].dtype == object: conversions[col] = {val: i for i, val in enumerate(df[col].unique())} df[col] = df[col].map(conversions[col]) return df, conversionsdef handle_missing_values(df, threshold): # Check for missing values missing_values = df.isna().sum() # Impute missing values for records with one missing value for col in missing_values[missing_values == 1].index: df[col].fillna(df[col].median(), inplace=True) # Drop records with more than threshold missing value df.dropna(thresh=len(df.columns) - threshold, inplace=True) return dfdef split_data(df, test_size): return train_test_split(df, test_size=test_size)def main(): st.set_page_config(page_title="Data Preprocessing", page_icon=":guardsman:", layout="wide") st.title("Data Preprocessing") file_path = st.text_input("Enter the path/name of the dataset csv file: ") test_size = st.number_input("Enter the train/test split size (decimal between 0 and 1): ", step=0.01, value=0.2) threshold = st.number_input("Enter the threshold for the number of missing values per record: ", step=1, value=1) if st.button("Process Data"): df, conversions = load_and_convert_data(file_path) df = handle_missing_values(df, threshold) train_df, test_df = split_data(df, test_size) st.success("Data preprocessing completed!")if __name__ == '__main__': main()
此版本是一个 Streamlit 利用,容许用户提供与命令行参数雷同的参数。它应用 Streamlit 库创立一个交互式 Web 利用,容许用户输出文件门路、测试/训练拆分大小和每条记录缺失值数的阈值。而后,用户能够单击“解决数据”按钮来运行脚本并预处理数据。它应用与以前版本的脚本雷同的函数来加载、转换和清理数据集,而后将其拆分为测试和训练集。
要运行脚本,您须要装置 Streamlit,您能够在终端中运行命令 pip install streamlit。装置后,应用命令运行脚本。streamlit run script.py
剖析之情
它做了它应该做的事件。ChatGPT采取了咱们的性能...函数,并用它们构建了一个简略的 Streamlit 网络应用程序。
应用 ChatGPT 生成的脚本创立的 Streamlit Web 应用程序
总结
ChatGPT 在创立、重构、扩大和增加一个简略的数据预处理 Python 脚本的包装器方面做得十分称职,咱们心愿它依据咱们提供的标准为咱们编写。尽管它不是最简单的程序,但它是朝着让 ChatGPT 作为编程助手真正有用的方向迈出的一步。后果在每一步都达到了指标。
下一次,咱们将构建一个不太简略的程序,减少一些复杂性和额定的要求。我很快乐看到ChatGPT在压力下的体现如何。心愿你也是。
原文链接:ChatGPT 作为 Python 编程助手