Python QuickStart for People Learning AI

原文:towardsdatascience.com/python-quickstart-for-people-learning-ai-58a1b76df0f4

Python 已经成为 AI 和数据科学的默认编程语言。尽管存在无代码解决方案,但学习如何编码仍然是构建完全定制的 AI 项目和产品所必需的。在这篇文章中,我分享了一个 Python AI 开发的入门级快速入门指南。我将介绍基础知识,然后分享一个具体的示例代码。


嵌入视频链接

Python是一种编程语言,即一种向计算机提供精确指令以完成我们无法或不想做的事情的方式[1]。

需要自动化一个没有现成解决方案的独特任务时,这很有用。例如,如果我想自动化撰写和发送个性化的会议后续跟进,我可以编写一个 Python 脚本来完成这项任务。

使用 ChatGPT 等工具,我们可以想象一个未来,在那里人们可以用普通的英语描述任何定制任务,而计算机就会完成它。然而,这样的消费级产品目前还不存在。在这样产品出现之前,了解(至少是稍微了解)Python 具有巨大的价值。

编码比以往任何时候都要容易

尽管当前的 AI 产品(例如 ChatGPT、Claude、Gemini)还没有使编程变得过时(至少目前还没有),但它们让学习如何编程变得比以往任何时候都要容易。我们现在都有一个称职且耐心的编码助手,他随时准备帮助我们学习。

结合“传统”的 Google 搜索问题解决方案,程序员现在可以更快地工作。例如,我慷慨地使用 ChatGPT 来编写示例代码和解释错误信息。这加速了我的进度,并在导航新技术堆栈时给了我更多的信心。

本指南面向对象

我写这篇文章时考虑的是特定类型的读者:那些试图进入 AI 领域并且已经进行过一些编码(例如,JS、HTML/CSS、PHP、Java、SQL、Bash/Powershell、VBA)但对 Python 却不太熟悉的人。

我将从 Python 基础知识开始,然后分享一个简单 AI 项目的示例代码。这不是一个全面的 Python 入门介绍。相反,它的目的是让你能够快速用 Python 编写你的第一个 AI 项目。

关于我 – 我是一名数据科学家和自学成才的 Python 程序员(5 年)。虽然关于软件开发我还有很多要学习,但在这里,我根据个人经验,概述了我认为 AI/数据科学项目中 Python 的必备基础知识


安装 Python

许多计算机都预装了 Python。要查看您的机器是否安装了它,请转到您的终端(Mac/Linux)或命令提示符(Windows),然后简单地输入“python”。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/df0fac475d77a3b2836b9f956eaffa11.png

在终端中使用 Python。图片由作者提供。

如果您没有看到这样的屏幕,您可以手动下载 Python(Windows/ Mac)。或者,可以安装Anaconda,这是一个流行的 Python 包系统,用于 AI 和数据科学。如果您遇到安装问题,请向您的首选 AI 助手寻求帮助

当 Python 运行时,我们现在可以开始编写一些代码。我建议我们在学习过程中在你的电脑上运行这些示例。你还可以从GitHub 仓库下载所有示例代码。

1) 数据类型

字符串与数字

数据类型(或简称“类型”)是一种对数据进行分类的方法,以便在计算机中适当地高效地处理

类型由可能的一组值和操作定义。例如,字符串任意字符序列(即文本),可以通过特定方式操作。尝试在您的命令行 Python 实例中输入以下字符串。

"this is a string">>'this is a string'
'so is this:-1*!@&04"(*&^}":>?'>>'so is this:-1*!@&04"(*&^}":>?'
"""and this is too!!11!""">>'andn this isn too!!11!'
"we can even "+"add strings together">>'we can even add strings together'

尽管字符串可以连接(即连接),但它们不能与数值数据类型(如int(即整数)或float(即带小数的数字))相加。如果我们尝试在 Python 中这样做,我们将得到一个错误消息,因为操作仅定义在兼容类型上。

# we can't add strings to other data types (BTW this is how you write comments in Python)"I am "+29>> TypeError: can only concatenate str(not"int") to str
# so we have to write 29 as a string"I am "+"29">>'I am 29'

列表与字典

除了基本的字符串、整数和浮点数类型之外,Python 还有用于结构化更大数据集合的类型。

其中一种类型是列表,一个有序的值集合。我们可以有字符串列表、数字列表、字符串**+**数字列表,甚至是列表的列表。

# a list of strings["a","b","c"]# a list of ints[1,2,3]# list with a string, int, and float["a",2,3.14]# a list of lists[["a","b"],[1,2],[1.0,2.0]]

另一个核心数据类型是字典,它由键值对序列组成,其中键是字符串值可以是任何数据类型。这是表示具有多个属性的数据的绝佳方式。

# a dictionary{"Name":"Shaw"}# a dictionary with multiple key-value pairs{"Name":"Shaw","Age":29,"Interests":["AI","Music","Bread"]}# a list of dictionaries[{"Name":"Shaw","Age":29,"Interests":["AI","Music","Bread"]},{"Name":"Ify","Age":27,"Interests":["Marketing","YouTube","Shopping"]}]# a nested dictionary{"User":{"Name":"Shaw","Age":29,"Interests":["AI","Music","Bread"]},"Last_login":"2024-09-06","Membership_Tier":"Free"}

2) 变量

到目前为止,我们已经看到了一些基本的 Python 数据类型和操作。然而,我们仍然缺少一个基本功能:变量。

变量提供对底层数据类型实例的抽象表示。例如,我可能创建一个名为 user_name 的变量,它代表一个包含我的名字“Shaw”的字符串。这使得我们能够编写灵活的程序,而不会局限于特定的值。

# creating a variable and printing it user_name ="Shaw"print(user_name)#>> Shaw

我们可以用其他数据类型做同样的事情,例如整数和列表。

# defining more variables and printing them as a formatted string.  user_age =29 user_interests =["AI","Music","Bread"]print(f"{user_name} is {user_age} years old. His interests include {user_interests}.")#>> Shaw is 29 years old. His interests include ['AI', 'Music', 'Bread'].

3) 创建脚本

现在我们示例代码片段越来越长,让我们看看如何创建我们的第一个脚本。这就是我们从命令行 编写和执行更复杂的程序 的方法。

要做到这一点,请在您的计算机上创建一个新的文件夹。我将其命名为 python-quickstart。如果您有一个喜欢的 IDE(例如,集成开发环境),请使用它来打开这个新文件夹并创建一个新的 Python 文件,例如,my-script.py。在那里,我们可以编写仪式性的“Hello, world”程序。

# ceremonial first programprint("Hello, world!")

如果您没有 IDE(不推荐),您可以使用基本的文本编辑器(例如,苹果的 TextEdit,Windows 的记事本)。在这些情况下,您可以通过使用 .py 扩展名而不是 .txt 来打开文本编辑器并保存一个新的文本文件。注意:如果您在 Mac 上使用 TextEditor,可能需要通过格式 > 制作纯文本将应用程序置于纯文本模式

然后,我们可以通过导航到包含我们新 Python 文件的文件夹并运行以下命令来使用终端(Mac/Linux)或命令提示符(Windows)运行此脚本。

python my-script.py 

恭喜!您运行了您的第一个 Python 脚本。您可以随意 通过复制粘贴即将出现的代码示例并重新运行脚本来扩展此程序,以查看它们的输出。

4) 循环和条件

Python(或任何其他编程语言)的两个基本功能是循环和条件。

循环允许我们 多次运行特定的代码块。最受欢迎的是 for 循环,它在迭代变量时运行相同的代码。

# a simple for loop iterating over a sequence of numbersfor i inrange(5):print(i)# print ith element# for loop iterating over a list user_interests =["AI","Music","Bread"]for interest in user_interests:print(interest)# print each item in list# for loop iterating over items in a dictionary user_dict ={"Name":"Shaw","Age":29,"Interests":["AI","Music","Bread"]}for key, value in user_dict.items():print(key,"=", value)# print each key and corresponding value

另一个核心功能是 条件,例如 if-else 语句,它 使我们能够编写逻辑。例如,我们可能想要检查用户是否为成年人或评估他们的智慧。

# check if user is 18 or olderif user_dict["Age"]>=18:print("User is an adult")# check if user is 1000 or older, if not print they have much to learnif user_dict["Age"]>=1000:print("User is wise")else:print("User has much to learn")

在 for 循环中使用条件是常见的,可以根据特定条件应用不同的操作,例如计算对面包感兴趣的用户数量。

# count the number of users interested in bread user_list =[{"Name":"Shaw","Age":29,"Interests":["AI","Music","Bread"]},{"Name":"Ify","Age":27,"Interests":["Marketing","YouTube","Shopping"]}] count =0# intialize countfor user in user_list:if"Bread"in user["Interests"]: count = count +1# update countprint(count,"user(s) interested in Bread")

5) 函数

函数是我们可以在特定数据类型上执行的 操作

我们已经看到了一个基本函数 print(),它为任何数据类型定义。然而,还有一些其他值得了解的实用函数。

# print(), a function we've used several times alreadyfor key in user_dict.keys():print(key,":", user_dict[key])# type(), getting the data type of a variablefor key in user_dict.keys():print(key,":",type(user_dict[key]))# len(), getting the length of a variablefor key in user_dict.keys():print(key,":",len(user_dict[key]))# TypeError: object of type 'int' has no len()

我们可以看到,与 print()type() 不同,len() 并不是为所有数据类型定义的,所以当它应用于一个整数时,会抛出一个错误。还有其他几个这样的 类型特定函数

# string methods# --------------# make string all lowercaseprint(user_dict["Name"].lower())# make string all uppercaseprint(user_dict["Name"].upper())# split string into list based on a specific character sequenceprint(user_dict["Name"].split("ha"))# replace a character sequence with anotherprint(user_dict["Name"].replace("w","whin"))
# list methods# ------------# add an element to the end of a list user_dict["Interests"].append("Entrepreneurship")print(user_dict["Interests"])# remove a specific element from a list user_dict["Interests"].pop(0)print(user_dict["Interests"])# insert an element into a specific place in a list user_dict["Interests"].insert(1,"AI")print(user_dict["Interests"])
# dict methods# ------------# accessing dict keysprint(user_dict.keys())# accessing dict valuesprint(user_dict.values())# accessing dict itemsprint(user_dict.items())# removing a key user_dict.pop("Name")print(user_dict.items())# adding a key user_dict["Name"]="Shaw"print(user_dict.items())

虽然核心 Python 函数很有帮助,但真正的力量来自于创建 用户定义函数执行自定义操作。此外,自定义函数允许我们编写更干净的代码。例如,以下是一些以前代码片段重新打包为用户定义函数。

# define a custom functiondefuser_description(user_dict):""" Function to return a sentence (string) describing input user """returnf'{user_dict["Name"]} is {user_dict["Age"]} years old and is interested in {user_dict["Interests"][0]}.'# print user description description = user_description(user_dict)print(description)# print description for a new user! new_user_dict ={"Name":"Ify","Age":27,"Interests":["Marketing","YouTube","Shopping"]}print(user_description(new_user_dict))
# define another custom functiondefinterested_user_count(user_list, topic):""" Function to count number of users interested in an arbitrary topic """ count =0for user in user_list:if topic in user["Interests"]: count = count +1return count # define user list and topic user_list =[user_dict, new_user_dict] topic ="Shopping"# compute interested user count and print it count = interested_user_count(user_list, topic)print(f"{count} user(s) interested in {topic}")

6) 库,pip,& venv

尽管我们可以使用核心 Python 实现任意程序,但对于某些用例来说,这可能会非常耗时。Python 的一个关键优势是其 充满活力的开发者社区和强大的软件包生态系统。您可能想要用核心 Python 实现的大部分内容(可能)已经作为开源库存在。

我们可以使用 Python 的原生包管理器 pip 安装这样的包。要安装新包,我们从命令行运行 pip 命令。以下是如何安装 numpy 的示例,这是一个实现基本数学对象和操作的基本数据科学库。

pip install numpy 

在我们安装了 numpy 之后,我们可以将其导入到一个新的 Python 脚本中,并使用它的一些数据类型和函数。

import numpy as np # create a "vector" v = np.array([1,3,6])print(v)# multiply a "vector"print(2*v)# create a matrix X = np.array([v,2*v, v/2])print(X)# matrix multiplicationprint(np.matmul(X,v))

之前的 pip 命令将 numpy 添加到了我们的基础 Python 环境中。或者,创建所谓的 虚拟环境 是一种最佳实践。这些是 可以轻松互换用于不同项目的 Python 库集合

这是创建名为 my-env 的新虚拟环境的方法。

python -m venv my-env 

然后,我们可以激活它。

# mac/linux source my-env/bin/activate # windows.my-envScriptsactivate.bat 

最后,我们可以使用 pip 安装新的库,例如 numpy。

pip install numpy 

_ 注意:如果您使用的是 Anaconda,请查看创建新 conda 环境的 实用速查表。_

在人工智能和数据科学中,还有许多其他库被广泛使用。以下是构建 AI 项目的一些有用的库的非全面概述。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/f07f634c1c5a4b076e6304a69fad16e4.png

这是一个关于数据科学和人工智能 Python 库的非全面概述。图片由作者提供。

示例代码:从研究论文中提取摘要和关键词

既然我们已经接触到了 Python 的基础知识,让我们看看如何用它来实现一个简单的 AI 项目。在这里,我将使用 OpenAI API 来创建一个研究论文摘要器和关键词提取器。

与本指南中的其他所有代码片段一样,示例代码可在 GitHub 仓库 中找到。


安装依赖

我们首先安装一些有用的库。您可以使用我们之前创建的相同 my-env 环境,或者创建一个新的环境。然后,您可以使用 GitHub 仓库 中的 requirements.txt 文件安装所有必需的包。

pip install -r requirements.txt 

这行代码会扫描 requirements.txt 中列出的每个库,并安装它们。

导入

接下来,我们可以创建一个新的 Python 脚本并导入所需的库。

import fitz # PyMuPDFimport openai import sys 

接下来,为了使用 OpenAI 的 Python API,我们需要导入一个 AI 密钥。这里有一种实现方式。

from sk import my_sk # Set up your OpenAI API key openai.api_key = my_sk 

注意,sk 不是一个 Python 库。相反,它是一个单独的 Python 脚本,它定义了一个变量,my_sk,这是一个 由我的 OpenAI API 密钥组成的字符串,即一个唯一的(且秘密的)令牌,允许使用 OpenAI 的 API。

我在 上一篇文章 中分享了一个关于 API、OpenAI API 以及设置 API 密钥的入门介绍。

破解 OpenAI (Python) API

读取 PDF

接下来,我们将创建一个函数,给定保存为 .pdf 文件的论文路径,将从中提取摘要。

# Function to read the first page of a PDF and extract the abstractdefextract_abstract(pdf_path):# Open the PDF file and grab text from the 1st pagewith fitz.open(pdf_path)as pdf: first_page = pdf[0] text = first_page.get_text("text")# Extract the abstract (assuming the abstract starts with 'Abstract')# find where abstract starts start_idx = text.lower().find('abstract')# end abstract at introduction if it exists on 1st pageif'introduction'in text.lower(): end_idx = text.lower().find('introduction')else: end_idx =None# extract abstract text abstract = text[start_idx:end_idx].strip()# if abstract appears on 1st page return it, if not resturn Noneif start_idx !=-1: abstract = text[start_idx:end_idx].strip()return abstract else:returnNone

使用 LLM 概述

现在我们有了摘要文本,我们可以使用 LLM 来总结它并生成关键词。在这里,我定义了一个函数,将摘要传递给 OpenAI 的 GPT-4o-mini 模型来完成这项工作。

# Function to summarize the abstract and generate keywords using OpenAI APIdefsummarize_and_generate_keywords(abstract):# Use OpenAI Chat Completions API to summarize and generate keywords prompt =f"Summarize the following paper abstract and generate (no more than 5) keywords:nn{abstract}"# make api call response = openai.chat.completions.create( model="gpt-4o-mini", messages=[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content": prompt}], temperature =0.25)# extract response summary = response.choices[0].message.content return summary 

将所有内容整合在一起

最后,我们可以使用我们定义的用户函数为任何通过命令行传递给程序的论文生成摘要和关键词。

# Get the PDF path from the command-line arguments pdf_path = sys.argv[1]# Extract abstract from the PDF abstract = extract_abstract(pdf_path)# if abstract exists on first page, print summary.if abstract:# Summarize and generate keywords summary = summarize_and_generate_keywords(abstract)print(summary)else:print("Abstract not found on the first page.")

然后,我们可以从命令行执行我们的程序。

python summarize-paper.py "files/attention-is-all-you-need.pdf"
Output: The paper introduces the Transformer, a novel network architecture for sequence transduction tasks that relies solely on attention mechanisms, eliminating the need for recurrent and convolutional structures. The Transformer demonstrates superior performance in machine translation tasks, achieving a BLEU score of 28.4 on the WMT 2014 English-to-German translation and a state-of-the-art score of 41.8 on the English-to-French translation task,while also being more efficient in training time. Additionally, the Transformer shows versatility by successfully applying to English constituency parsing with varying amounts of training data.**Keywords:** Transformer, attention mechanisms, machine translation, BLEU score, neural networks.
YouTube-Blog/python-quickstart at main · ShawhinT/YouTube-Blog

接下来是什么?

在这里,我们涵盖了 Python 的基础知识并实现了我们的第一个 AI 项目!尽管我们已经覆盖了很多内容,但还有更多要学习。

下一步是实施你自己的 AI 项目。这是持续学习的最佳方式。然而,在我们继续之前,这里有一些提示。

  • 在遇到困难时,请慷慨地使用 Google 和 ChatGPT
  • “弄懂它” 是作为程序员必须培养的关键技能
  • 查看数据科学家最喜欢的工具:Jupyter Notebooks
  • 从本指南的示例中破解以开始!

我的网站: www.shawhintalebi.com/

[1] AI Python 初学者指南

Read more

初识Linux —— make和makefile自动化构建工具

初识Linux —— make和makefile自动化构建工具

什么是make/makefile 本篇文章对于图片即内容详解,已同步到博主gitee:基本工具使用/make和makefile.png - 努力学习的小廉 在之前写代码的过程中,我们都是对一个文件进行编译链接(gcc编译),但是如果一个项目中,源代码文件非常的多,我们总不能一个一个的进行编译链接,这也太麻烦了;所以现在就来学习make/makefile实现自动化构建 make是一个命令工具,是一个解释makefile在指令的命令工具,大多数的IDE都存在这个命令。 makefile成为一种在工程方面的编译方法。 makefile是一个文件,make是一个命令;二者搭配使用来完成项目的自动化构建makefile的好处就是自动化构建,写好makefile文件以后就只需make命令就可以完成项目工程的自动化构建,提点高了软件开发的效率 其实会不会写makefile文件,也侧面反映了其是否具备完成大型工程的能力 在一个工程中源代码文件,按照类型、功能、模块分别放到了若干个目录下,makefile定义一系列的规则来指定哪些文件需要先编译、哪些文件需要后编译,哪些文件需要重新编译,甚

By Ne0inhk
Azure终极目标:Java应用0运维?5步实现!

Azure终极目标:Java应用0运维?5步实现!

🔥关注墨瑾轩,带你探索编程的奥秘!🚀 🔥超萌技术攻略,轻松晋级编程高手🚀 🔥技术宝库已备好,就等你来挖掘🚀 🔥订阅墨瑾轩,智趣学习不孤单🚀 🔥即刻启航,编程之旅更有趣🚀 5步,实现Java应用零运维 第1步:容器化(Docker)——不是可选,是“基础基石” 为什么是基石? * 环境一致性:开发、测试、生产环境统一 * 依赖隔离:JDK、应用、库打包在一起 * Azure支持:ACR、AKS、App Service for Containers原生支持 Java + Docker实现: # Dockerfile FROM eclipse-temurin:17-jre-alp

By Ne0inhk
Linux 实战:从零实现动态进度条(含缓冲区原理与多版本优化)

Linux 实战:从零实现动态进度条(含缓冲区原理与多版本优化)

🔥草莓熊Lotso:个人主页 ❄️个人专栏: 《C++知识分享》《Linux 入门到实践:零基础也能懂》 ✨生活是默默的坚持,毅力是永久的享受! 🎬 博主简介: 文章目录 * 前言: * 一. 核心预备知识:掌握三大关键点,轻松避开进度条开发常见误区 * 1.1 回车(\r)与换行(\n)的本质区别解析 * 1.2 深入理解行缓冲区运行机制 * 1.3 进度条的核心构成元素详解 * 二. 实战开发:打造动态彩色进度条 * 2.1 基础版进度条模拟实现(演示原理,实际应用较少) * 2.2 自动化构建流程:Makefile编写详解 * 2.3 头文件设计(process.h):接口函数声明 * 2.4

By Ne0inhk
Docker Network 命令:容器网络管理的完整指南

Docker Network 命令:容器网络管理的完整指南

Docker Network 命令:容器网络管理的完整指南 * 一、Docker 网络概述 * 1.1 Docker 网络架构 * 1.2 默认网络类型 * 二、核心命令详解 * 2.1 网络列表查看(docker network ls) * 2.2 网络创建(docker network create) * 2.3 网络详情查看(docker network inspect) * 三、网络连接管理 * 3.1 容器连接网络(docker network connect) * 3.2 容器断开网络(docker network disconnect) * 四、高级网络配置

By Ne0inhk