Python人工智能实例如何快速入门实践?

99ANYc3cd6 人工智能 7

入门级 - 图像分类 (使用预训练模型)

这是体验 AI 最直接、最有趣的方式之一,我们将使用一个在大型数据集上预训练好的模型,让它识别图片中的物体。

Python人工智能实例如何快速入门实践?-第1张图片-广州国自机器人
(图片来源网络,侵删)

技术栈:

  • Python: 核心编程语言
  • TensorFlow/Keras: 高级深度学习框架
  • Pillow (PIL): 图像处理库

目标: 让 AI 识别你上传的一张图片,告诉你图片里是什么。

步骤 1: 环境准备

你需要安装必要的库,打开你的终端或命令行工具,运行:

pip install tensorflow pillow numpy

步骤 2: 编写 Python 代码

创建一个名为 image_classifier.py 的文件,并粘贴以下代码:

Python人工智能实例如何快速入门实践?-第2张图片-广州国自机器人
(图片来源网络,侵删)
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
# 1. 加载预训练的模型 (MobileNetV2, 在 ImageNet 数据集上训练)
# weights='imagenet' 表示使用在 ImageNet 上训练好的权重
print("正在加载预训练模型...")
model = keras.applications.MobileNetV2(weights='imagenet')
print("模型加载完成!")
# 2. 图像预处理函数
def preprocess_image(img_path):
    # 加载图像,并调整大小为模型输入大小 (224, 224)
    img = image.load_img(img_path, target_size=(224, 224))
    # 将图像转换为数组
    img_array = image.img_to_array(img)
    # 扩展维度,因为模型期望一个批次的图像 (batch_size, height, width, channels)
    img_array = np.expand_dims(img_array, axis=0)
    # 使用 MobileNetV2 的预处理器进行标准化
    img_array = keras.applications.mobilenet_v2.preprocess_input(img_array)
    return img_array, img
# 3. 图像预测和结果展示函数
def predict_and_show(img_path):
    # 预处理图像
    processed_img, original_img = preprocess_image(img_path)
    # 使用模型进行预测
    predictions = model.predict(processed_img)
    # 解码预测结果 (将输出转换为人类可读的标签和概率)
    decoded_predictions = keras.applications.mobilenet_v2.decode_predictions(predictions, top=3)[0]
    # 打印预测结果
    print("\n--- 预测结果 ---")
    for i, (imagenet_id, label, score) in enumerate(decoded_predictions):
        print(f"{i+1}: {label} ({score:.2f})")
    # 使用 Matplotlib 显示图片和预测结果
    plt.imshow(original_img)
    plt.axis('off')
    # 在图片上添加标题,显示最可能的预测结果
    top_prediction = decoded_predictions[0]
    plt.title(f"预测: {top_prediction[1]} ({top_prediction[2]:.2f})", fontsize=16)
    plt.show()
# --- 主程序 ---
if __name__ == "__main__":
    # 请将 'your_image.jpg' 替换为你自己的图片路径
    # 你可以从网上下载一张常见的物体图片,比如猫、狗、汽车等
    image_path = 'your_image.jpg' 
    # 检查文件是否存在
    try:
        predict_and_show(image_path)
    except FileNotFoundError:
        print(f"错误: 文件 '{image_path}' 未找到。")
        print("请将一张图片 ('cat.jpg') 放在与此脚本相同的目录下,并修改代码中的 'image_path'。")
    except Exception as e:
        print(f"发生错误: {e}")

步骤 3: 运行和体验

  1. 找一张你喜欢的图片(比如猫、狗、汽车、香蕉等),把它和 image_classifier.py 放在同一个文件夹里。
  2. 将代码中的 image_path = 'your_image.jpg' 修改为你自己的图片名。
  3. 在终端中运行脚本:
    python image_classifier.py

你会看到什么?

  • 程序会加载模型(第一次运行时需要下载模型文件,可能需要一些时间)。
  • 然后会显示你的图片,并在下方打印出 AI 认为图片中是什么东西,以及置信度(概率)。
  • 如果你放了一张猫的照片,它可能会输出:
    --- 预测结果 ---
    1: tabby (0.85)
    2: Egyptian_cat (0.10)
    3: tiger_cat (0.03)

    并在图片上显示 "预测: tabby (0.85)"。

这个实例的核心思想: 我们不需要从零开始教 AI 识别猫。迁移学习是 AI 领域一个非常重要的概念,我们利用一个已经在海量数据(ImageNet 包含 140 万张图片、1000 个类别)上训练好的模型,让它直接为我们服务,这就像一个已经精通了多种语言的学生,学习一门新语言会快得多。


进阶级 - 聊天机器人

这个实例将带你构建一个简单的、基于检索的聊天机器人,它不会像 ChatGPT 那样有“思考”能力,但它能根据你的问题,从它“知识库”中找到最相关的回答。

Python人工智能实例如何快速入门实践?-第3张图片-广州国自机器人
(图片来源网络,侵删)

技术栈:

  • Python: 核心编程语言
  • Scikit-learn: 用于文本特征提取(TF-IDF)和相似度计算(余弦相似度)
  • NLTK/NLTK_data: 用于文本分词(如果需要更复杂的处理,但这里 Scikit-learn 的分词已足够)

目标: 创建一个可以根据关键词回答预设问题的机器人。

步骤 1: 环境准备

pip install scikit-learn nltk

安装 NLTK 的数据包(只需要运行一次):

import nltk
nltk.download('punkt')

步骤 2: 准备知识库

创建一个名为 chatbot_data.py 的文件,用来存储机器人的“知识”,这是一个简单的字典,键是问题,值是回答。

# chatbot_data.py
# 我们将问题标准化为小写,方便匹配
BOT_KNOWLEDGE_BASE = {
    "你好": "你好!很高兴见到你。",
    "你好吗": "我只是一个程序,但我感觉很好!你呢?",
    "你是谁": "我是一个简单的聊天机器人,由 Python 和 Scikit-learn 构建。",
    "你叫什么名字": "你可以叫我 Python 小助手。",
    "再见": "再见!希望很快能再聊。",
    "感谢": "不客气,随时为您服务。",
    "你能做什么": "我可以回答一些预设的问题,或者陪你聊聊天。",
    "天气怎么样": "我无法实时获取天气信息,抱歉。",
    "你喜欢什么": "我喜欢处理数据和回答问题!",
    "你是怎么工作的": "我通过计算你输入的问题和我知识库中问题的相似度,来找到最合适的回答。"
}

步骤 3: 编写聊天机器人核心代码

创建一个名为 simple_chatbot.py 的文件:

import random
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import chatbot_data # 导入我们的知识库
# 1. 准备语料库
# 将知识库的键(问题)和值(回答)合并成一个大的文本列表
corpus_raw = list(chatbot_data.BOT_KNOWLEDGE_BASE.keys()) + list(chatbot_data.BOT_KNOWLEDGE_BASE.values())
# 2. 文本预处理函数
def preprocess_text(text):
    # 转换为小写
    text = text.lower()
    # 移除标点符号
    text = text.translate(str.maketrans('', '', string.punctuation))
    return text
# 3. 构建向量器和相似度计算器
print("正在初始化聊天机器人...")
# 预处理所有文本
processed_corpus = [preprocess_text(sentence) for sentence in corpus_raw]
# 创建 TF-IDF 向量器
# stop_words='english' 会移除常见的英文停用词 (a, an, the, is, etc.)
vectorizer = TfidfVectorizer(stop_words='english')
# 将所有文本转换为 TF-IDF 向量
tfidf_matrix = vectorizer.fit_transform(processed_corpus)
print("机器人已准备就绪!\n")
# 4. 聊天循环
def get_response(user_input):
    # 预处理用户输入
    user_input_processed = preprocess_text(user_input)
    # 将用户输入也转换为 TF-IDF 向量
    user_input_vector = vectorizer.transform([user_input_processed])
    # 计算用户输入与语料库中所有句子的相似度
    cosine_similarities = cosine_similarity(user_input_vector, tfidf_matrix)
    #

标签: Python人工智能入门实例教程 人工智能Python快速实践指南 Python AI项目零基础实战案例

抱歉,评论功能暂时关闭!