ChatGPT 作为 Python 编程助手

这篇具有很好参考价值的文章主要介绍了ChatGPT 作为 Python 编程助手。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

推荐:使用 NSDT场景编辑器 助你快速搭建可编辑的3D应用场景

简单的数据处理脚本


我认为一个好的起点是某种数据处理脚本。由于我打算让 ChatGPT 之后使用各种 Python 库编写一些机器学习脚本,这似乎是一个合理的起点。

目标


首先,我想尝试加载数据集;确保所有数据集值都是数值,或将其转换为数值;检查缺失值;并将数据集拆分为训练集和测试集。

提示


编写一个 Python 脚本来执行以下操作:
- 将数据集从磁盘上的 csv 加载到 Pandas 数据帧- 确保数据集完全是数字;将字符串值转换为数字,并在字典中跟踪此转换以供以后
引用 - 检查数据帧中的缺失值,并为具有一个缺失值的任何记录插补缺失值;完全删除具有多个缺失值
的记录 - 将数据集拆分为测试和训练集

回应

import pandas as pd

# Load dataset from csv to DataFrame
df = pd.read_csv('dataset.csv')

# 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])

# 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)

# Split dataset into test and training sets
from sklearn.model_selection import train_test_split
train_df, test_df = train_test_split(df, test_size=0.2)

注意:脚本从csv文件名“dataset.csv”加载数据集,并将数据帧拆分为80/20比率的测试和训练集。如果要使用不同的文件名或比率,请相应地更改路径/比率。

分析之情


ChatGPT生成了一个有用的脚本。它决定了数据集名称以及训练/测试拆分百分比,并记录了这两个点以及如何根据需要更改它们。总的来说,任务完成了。

重构我们的代码

目标


现在我们有一个可以执行某些操作的脚本,让我们稍微重构一下。良好编码的基石是使用函数来逻辑地组织代码,促进重用,并确保您不会重复自己。

提示


重写上面的脚本以使用一系列有意义的函数

回应

import pandas as pd
from sklearn.model_selection import train_test_split

def 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, conversions

def 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 df

def split_data(df, test_size):
    return train_test_split(df, test_size=test_size)

# Use the functions
file_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)

在这里,我使用了三个函数:

1. load_and_convert_data(file_path) 加载 CSV 数据集并将字符串值转换为数字。
2. handle_missing_values(df) 处理数据集中的缺失值。
3. split_data(df,test_size)将数据集拆分为测试和训练集。

主脚本使用这些函数来加载、转换和清理数据集,然后将其拆分为测试和训练集。

数据集的路径和测试比率是这些函数的输入。

分析之情


如果你看一下 ChatGPT 输出的第一个脚本,你可能会看到一些相当明显的线条,你会画出哪些功能将被分成函数。我当然做到了。在这方面,ChatGPT 完全按照我的预期做了。同样,已经生成了一个称职的脚本。

扩展我们的代码

目标


好的,我们的脚本现在看起来好一点,因为它使用了一些函数进行组织。接下来,让我们稍微扩展脚本,以便用户可以在运行脚本时指定一些参数。

提示


重写上述程序,以参数的形式从命令行请求以下内容,并在程序中使用它们:
- 数据集 CSV 文件的
路径/名称 - 训练/测试拆分大小
- 每条记录要丢弃的缺失值数的阈值,之后删除整个记录,而不是插补缺失值

回应

import pandas as pd
import argparse
from sklearn.model_selection import train_test_split

def 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, conversions

def 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 df

def 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 pd
import streamlit as st
from sklearn.model_selection import train_test_split

def 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, conversions

def 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 df

def 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 作为 Python 编程助手,chatgpt,python,人工智能


使用 ChatGPT 生成的脚本创建的 Streamlit Web 应用程序

总结


ChatGPT 在创建、重构、扩展和添加一个简单的数据预处理 Python 脚本的包装器方面做得非常称职,我们希望它根据我们提供的规范为我们编写。虽然它不是最复杂的程序,但它是朝着让 ChatGPT 作为编程助手真正有用的方向迈出的一步。结果在每一步都达到了目标。

下一次,我们将构建一个不太简单的程序,增加一些复杂性和额外的要求。我很高兴看到ChatGPT在压力下的表现如何。希望你也是。

原文链接:ChatGPT 作为 Python 编程助手 (mvrlink.com)文章来源地址https://www.toymoban.com/news/detail-633935.html

到了这里,关于ChatGPT 作为 Python 编程助手的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【一分钟学会】用python做一个语音对话ChatGPT的程序——打造私人语音助手

            本项目灵感来源是我的一个专业课程设计,当时耗时近四天在网上都没找到十分有用的信息。         以下是本项目完整的步骤流程,算是对自己工作的一个阶段性总结。希望同感兴趣的小伙伴们相互探讨、交流和学习。 一、准备工作         首先,需要准备①

    2024年02月11日
    浏览(18)
  • ChatGPT编程:让AI成为你的编程助手

    ChatGPT无限次数: 点击直达 html 作为一名有着10年经验的CSDN网站原创文章优质创作者,我对最新的技术趋势一直保持着敏锐的关注。最近,随着人工智能技术的不断发展,ChatGPT作为一种基于大型预训练语言模型的对话AI,在编程领域中展现出了强大的应用潜力。 ChatGPT是由Open

    2024年04月16日
    浏览(19)
  • Android Studio类ChatGpt的免费AI编程助手

    ChatGpt大火,带动了AI工具的发展,介绍两款免费的AI编程助手,一款用于输入自动输出代码,一款则是自动补全提示. 可支持大部分代码编辑器,这里主要介绍Android Studio上安装使用. 支持chat,可输入自动输出代码 File - Settings -Plugins,输入bito搜索点击Install.

    2024年02月08日
    浏览(22)
  • chatgpt赋能python:Python:一门强大的编程语言

    Python是一款高级编程语言,以其简单易用和多功能而闻名于世。Python首次发布于1989年,如今已成为许多开发者的首选编程语言。Python特别适合于数据处理、机器学习、人工智能等领域。 Python的流行程度越来越高,因为它几乎可以在任何领域使用,并且能够解决用其他编程语

    2024年02月06日
    浏览(20)
  • chatgpt赋能python:Python编程教程:如何用Python写抢购程序

    随着网购的流行和限量商品的推出,抢购已经成为了一个非常热门的话题。有些人甚至会通过软件或程序来提高他们成功抢到商品的机会。在本篇文章中,我们将介绍如何用Python编写一个简单易用的抢购程序,帮助您在抢购商品时获得竞争优势。 在编写Python抢购程序之前,您

    2024年02月07日
    浏览(20)
  • chatgpt赋能python:Python编程:按键盘上哪个键运行?

    Python是一种高级编程语言,它以简洁易懂的语法和动态类型的特性,成为了Web开发、数据科学、机器学习等领域中的热门工具。在使用Python进行编程时,最常使用的方式之一是在键盘上输入命令,来执行程序或调试代码。但你是否曾经想过,按下哪个键才能运行你的代码?

    2024年02月04日
    浏览(17)
  • chatgpt赋能python:Python与SICP:重塑编程的未来

    随着现代生活的发展,计算机在我们的生活中扮演越来越重要的角色。而Python语言则成为了众多开发者使用的首选语言。作为一门高级编程语言,Python在开发业界广受欢迎,并且得到了MIT计算机科学家们的青睐。自1985年诞生已来,Python作为一门先进而又简约的语言,极大地影

    2024年02月06日
    浏览(38)
  • chatgpt赋能python:Python循环次数:实现高效编程的关键

    在编写Python程序时,循环次数是一个经常需要关注的问题。循环次数过多会导致程序执行效率低下,甚至可能引起性能问题。因此,如何控制循环次数成为实现高效编程的关键。本文将介绍Python中循环次数的相关知识,为你在编写Python程序时提供指导。 在Python中,可以使用

    2024年02月08日
    浏览(23)
  • chatgpt赋能python:Python编程中如何退回上一步操作

    在Python编程中,退回上一步操作是开发过程中经常遇到的问题。当你不小心输入了错误的代码或者执行了不想要的操作后,可能需要撤销这些更改。这篇文章将介绍几种在Python编程中退回上一步操作的方法。 在大多数操作系统中,使用Ctrl + Z组合键可以撤销上一步操作。在

    2024年02月15日
    浏览(20)
  • ChatGPT4助力Python数据分析与可视化、人工智能建模及论文高效撰写

    2022年11月30日,可能将成为一个改变人类历史的日子——美国人工智能开发机构OpenAI推出了聊天机器人ChatGPT3.5,将人工智能的发展推向了一个新的高度。2023年4月,更强版本的ChatGPT4.0上线,文本、语音、图像等多模态交互方式使其在各行各业的应用呈现了更多的可能性。202

    2024年02月03日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包