【Python入门系列】第十六篇:Python人工智能和深度学习

news/2024/4/20 15:21:09/文章来源:https://blog.csdn.net/qq_38628970/article/details/131717191

【Python入门系列】第十六篇:Python人工智能和深度学习

文章目录

  • 前言
  • 一、Python在人工智能中的应用
  • 二、深度学习的基本原理
  • 三、Python实现深度学习的示例代码
    • 1、简单卷积神经网络
    • 2、图像分类:使用深度学习模型对图像进行分类。
    • 3、文本生成:使用循环神经网络(RNN)生成文本。
    • 4、人脸识别:使用深度学习模型进行人脸识别。
    • 5、情感分析:使用深度学习模型进行文本情感分析。
    • 6、机器翻译:使用神经网络进行机器翻译。
    • 7、文本生成:使用循环神经网络生成文本。
    • 8、强化学习:使用深度强化学习训练智能体玩游戏。
  • 总结


前言

人工智能(Artificial Intelligence,简称AI)和深度学习(Deep Learning)是当今科技领域的热门话题。Python作为一种功能强大且易于学习的编程语言,在人工智能和深度学习领域中扮演着重要的角色。本文将介绍Python在人工智能和深度学习中的应用以及相关的技术知识。

一、Python在人工智能中的应用

Python在人工智能领域中具有广泛的应用,涵盖了数据处理、模型构建、算法实现等多个方面。以下是Python在人工智能中常用的库和工具:

  1. NumPy:NumPy是Python中用于科学计算的基础库,提供了高效的多维数组(ndarray)操作功能,适用于大规模数据处理和数值计算。

  2. Pandas:Pandas是Python中用于数据处理和分析的库,提供了灵活且高效的数据结构和数据操作方法,可用于数据清洗、数据转换和数据分析等任务。

  3. Scikit-learn:Scikit-learn是Python中常用的机器学习库,提供了丰富的机器学习算法和工具,包括分类、回归、聚类、降维等常用算法,方便用户进行模型训练和评估。

  4. TensorFlow:TensorFlow是由Google开发的开源深度学习框架,提供了丰富的深度学习算法和工具,支持构建和训练各种类型的神经网络模型。

5.Keras:Keras是一个高级神经网络API,可以作为TensorFlow等后端库的接口,简化了模型构建和训练的过程,使得深度学习更加易于上手和快速实现。

二、深度学习的基本原理

深度学习是一种基于神经网络的机器学习方法,其核心思想是通过多层次的神经网络模型来学习和提取数据的高级特征,实现对复杂模式和规律的识别和理解。

在深度学习中,常用的神经网络模型包括卷积神经网络(Convolutional Neural Network,简称CNN)、循环神经网络(Recurrent Neural Network,简称RNN)和生成对抗网络(Generative Adversarial Network,简称GAN)等。这些模型通过不同的网络结构和算法实现了对图像、语音、文本等数据的处理和分析。

三、Python实现深度学习的示例代码

1、简单卷积神经网络

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense# 构建模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax'))# 编译模型
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])# 训练模型
model.fit(train_images, train_labels, epochs=10, batch_size=64)# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)

以上代码展示了一个简单的卷积神经网络模型的构建和训练过程,用于对图像进行分类。

2、图像分类:使用深度学习模型对图像进行分类。

import tensorflow as tf# 加载预训练的模型
model = tf.keras.applications.MobileNetV2()# 加载图像
image = tf.keras.preprocessing.image.load_img('image.jpg', target_size=(224, 224))
input_image = tf.keras.preprocessing.image.img_to_array(image)
input_image = tf.keras.applications.mobilenet_v2.preprocess_input(input_image[tf.newaxis, ...])# 预测图像类别
predictions = model.predict(input_image)
predicted_class = tf.keras.applications.mobilenet_v2.decode_predictions(predictions, top=1)[0][0]print('Predicted class:', predicted_class[1])

3、文本生成:使用循环神经网络(RNN)生成文本。

import tensorflow as tf# 加载文本数据
text = open('text.txt', 'rb').read().decode(encoding='utf-8')# 构建字符级的语言模型
vocab = sorted(set(text))
char_to_idx = {char: idx for idx, char in enumerate(vocab)}
idx_to_char = {idx: char for idx, char in enumerate(vocab)}
text_as_int = [char_to_idx[char] for char in text]# 构建训练样本
seq_length = 100
examples_per_epoch = len(text) // (seq_length + 1)
char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)
sequences = char_dataset.batch(seq_length + 1, drop_remainder=True)def split_input_target(chunk):input_text = chunk[:-1]target_text = chunk[1:]return input_text, target_textdataset = sequences.map(split_input_target)# 构建模型
model = tf.keras.Sequential([tf.keras.layers.Embedding(len(vocab), 256, batch_input_shape=[batch_size, None]),tf.keras.layers.GRU(1024, return_sequences=True, stateful=True, recurrent_initializer='glorot_uniform'),tf.keras.layers.Dense(len(vocab))
])# 训练模型
model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
model.fit(dataset, epochs=10)# 生成文本
def generate_text(model, start_string):num_generate = 1000input_eval = [char_to_idx[s] for s in start_string]input_eval = tf.expand_dims(input_eval, 0)text_generated = []model.reset_states()for _ in range(num_generate):predictions = model(input_eval)predictions = tf.squeeze(predictions, 0)predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()input_eval = tf.expand_dims([predicted_id], 0)text_generated.append(idx_to_char[predicted_id])return (start_string + ''.join(text_generated))generated_text = generate_text(model, start_string='The')
print(generated_text)

4、人脸识别:使用深度学习模型进行人脸识别。

import cv2
import dlib# 加载人脸检测器
detector = dlib.get_frontal_face_detector()
# 加载人脸识别模型
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')# 加载图像
image = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = detector(gray)
for face in faces:# 获取人脸关键点landmarks = predictor(gray, face)# 绘制人脸框和关键点cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 2)for n in range(68):x = landmarks.part(n).xy = landmarks.part(n).ycv2.circle(image, (x, y), 4, (0, 0, 255), -1)# 显示图像
cv2.imshow('Face Recognition', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

5、情感分析:使用深度学习模型进行文本情感分析。

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences# 加载数据
texts = ['这部电影太好看了!', '这个产品质量很差。', '这个餐厅的食物很美味。', '我对这个服务感到非常失望。']
labels = [1, 0, 1, 0]# 构建词汇表
tokenizer = Tokenizer()
tokenizer.fit_on_texts(texts)
word_index = tokenizer.word_index# 将文本转换为序列
sequences = tokenizer.texts_to_sequences(texts)
padded_sequences = pad_sequences(sequences)# 构建模型
model = tf.keras.Sequential([tf.keras.layers.Embedding(len(word_index) + 1, 100, input_length=padded_sequences.shape[1]),tf.keras.layers.GlobalAveragePooling1D(),tf.keras.layers.Dense(16, activation='relu'),tf.keras.layers.Dense(1, activation='sigmoid')
])# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])# 训练模型
model.fit(padded_sequences, labels, epochs=10)# 预测情感
test_text = ['这个电影真的很棒!']
test_sequence = tokenizer.texts_to_sequences(test_text)
test_padded_sequence = pad_sequences(test_sequence, maxlen=padded_sequences.shape[1])
prediction = model.predict(test_padded_sequence)
if prediction > 0.5:print('正面情感')
else:print('负面情感')

6、机器翻译:使用神经网络进行机器翻译。

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences# 加载数据
source_texts = ['I love this movie.', 'This product is amazing.', 'The food at this restaurant is delicious.']
target_texts = ['我喜欢这部电影。', '这个产品太棒了。', '这个餐厅的食物很美味。']# 构建源语言和目标语言的词汇表
source_tokenizer = Tokenizer()
source_tokenizer.fit_on_texts(source_texts)
source_word_index = source_tokenizer.word_index
target_tokenizer = Tokenizer()
target_tokenizer.fit_on_texts(target_texts)
target_word_index = target_tokenizer.word_index# 将文本转换为序列
source_sequences = source_tokenizer.texts_to_sequences(source_texts)
target_sequences = target_tokenizer.texts_to_sequences(target_texts)
source_padded_sequences = pad_sequences(source_sequences)
target_padded_sequences = pad_sequences(target_sequences)# 构建模型
model = tf.keras.Sequential([tf.keras.layers.Embedding(len(source_word_index) + 1, 100, input_length=source_padded_sequences.shape[1]),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(128)),tf.keras.layers.RepeatVector(target_padded_sequences.shape[1]),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(128, return_sequences=True)),tf.keras.layers.Dense(len(target_word_index) + 1, activation='softmax')
])# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')# 训练模型
model.fit(source_padded_sequences, target_padded_sequences, epochs=10)# 进行机器翻译
test_text = ['I love this restaurant.']
test_sequence = source_tokenizer.texts_to_sequences(test_text)
test_padded_sequence = pad_sequences(test_sequence, maxlen=source_padded_sequences.shape[1])
prediction = model.predict(test_padded_sequence)
predicted_sequence = np.argmax(prediction, axis=-1)
predicted_text = target_tokenizer.sequences_to_texts(predicted_sequence)
print(predicted_text)

7、文本生成:使用循环神经网络生成文本。

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences# 加载数据
text = "我喜欢这个电影。它很有趣。"
# 将文本拆分为句子
sentences = text.split("。")# 构建词汇表
tokenizer = Tokenizer()
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index# 将文本转换为序列
sequences = tokenizer.texts_to_sequences(sentences)
padded_sequences = pad_sequences(sequences)# 构建模型
model = tf.keras.Sequential([tf.keras.layers.Embedding(len(word_index) + 1, 100, input_length=padded_sequences.shape[1]),tf.keras.layers.GRU(128, return_sequences=True),tf.keras.layers.GRU(128),tf.keras.layers.Dense(len(word_index) + 1, activation='softmax')
])# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')# 训练模型
model.fit(padded_sequences, padded_sequences, epochs=10)# 生成文本
seed_text = "我喜欢"
for _ in range(5):sequence = tokenizer.texts_to_sequences([seed_text])[0]padded_sequence = pad_sequences([sequence], maxlen=padded_sequences.shape[1])prediction = model.predict(padded_sequence)predicted_word_index = np.argmax(prediction, axis=-1)[0]predicted_word = [word for word, index in word_index.items() if index == predicted_word_index][0]seed_text += predicted_word
print(seed_text)

8、强化学习:使用深度强化学习训练智能体玩游戏。

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adamenv = gym.make('CartPole-v1')
state_size = env.observation_space.shape[0]
action_size = env.action_space.nmodel = Sequential([Dense(24, input_dim=state_size, activation='relu'),Dense(24, activation='relu'),Dense(action_size, activation='linear')
])model.compile(loss='mse', optimizer=Adam())num_episodes = 1000
for episode in range(num_episodes):state = env.reset()state = np.reshape(state, [1, state_size])done = Falsescore = 0while not done:action = np.argmax(model.predict(state))next_state, reward, done, _ = env.step(action)next_state = np.reshape(next_state, [1, state_size])score += rewardstate = next_stateprint("Episode: {}, Score: {}".format(episode+1, score))# 在每个回合结束后,更新模型的权重print("训练完成!")arp

总结

Python作为一种简单易用且功能强大的编程语言,成为了人工智能和深度学习的首选工具之一。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_331282.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JavaWeb项目【SpringBoot】——图书项目4.0【源码】:SpringBoot版本 springboot相关技术 项目应用

目录 项目简介思考 & 改进1.Jsp都是同步请求---->改成异步Ajax【完成】2.前端用Jsp技术落后----->用Vue框架【完成】3.架构问题:配置数据和Java代码耦合【完成】3.SQL语句和Java代码耦合【完成】4.架构问题:servlet只能处理一个请求5.响应方式…

[论文分享]MR-MAE:重构前的模拟:用特征模拟增强屏蔽自动编码器

论文题目:Mimic before Reconstruct: Enhancing Masked Autoencoders with Feature Mimicking 论文地址:https://arxiv.org/abs/2303.05475 代码地址:https://github.com/Alpha-VL/ConvMAE(好像并未更新为MR-MAE模型) …

从Vue2到Vue3【零】——Vue3简介及创建

系列文章目录 内容链接从Vue2到Vue3【零】Vue3简介及创建 文章目录 系列文章目录前言一、Vue3的发布带来了什么1.1 性能提升1.2 源码升级1.3 支持TypeScript1.4 新特性 二、创建Vue3.0工程2.1 什么是Vite2.2 利用Vite创建Vue3.0工程2.3 利用vue-cli脚手架创建Vue3.0工程 三、 …

美团JVM面试题

1. 请解释一下对象创建的过程? Java对象创建的过程主要分为以下五个步骤: 类加载检查 Java虚拟机在读取一条new指令时候,首先检查能否在常量池中定位到这个类的符号引用,并且检查这个符号引用代表的类是否被加载、解析和初始化。如果没有&a…

C#开发的OpenRA游戏之维修按钮

C#开发的OpenRA游戏之维修按钮 前面分析物品的变卖按钮,如果理解这个流程,再看其它按钮的流程,其实是一样的,所以前面的文章是关键,只有理解通透的基础之上,才能继续往下。 维修按钮的存在价值,就是当建筑物受到敌方破坏,还没有完全倒掉之前,可以使用金币来进行修理。…

快速排序的非递归实现、归并排序的递归和非递归实现、基数排序、排序算法的时间复杂度

文章目录 快速排序的非递归三数取中法选取key快速排序三路划分 归并排序的递归归并排序的非递归计数排序稳定性排序算法的时间复杂度 快速排序的非递归 我们使用一个栈来模拟函数的递归过程,这里就是在利用栈分区间。把一个区间分为 [left,keyi-1][key][keyi1,right…

Android 进程与进程之间的通信--AIDL详细教程,以传递对象为例,两个app实现

我这里案例是 通过 IPC 传递对象 (以DemoBean类为例) 如下: AIDL 使用一种简单语法,允许您通过一个或多个方法(可接收参数和返回值)来声明接口。参数和返回值可为任意类型,甚至是 AIDL 生成的其…

如何将jar 包下载到自定义maven仓库

下载命令 mvn install:install-file -Dfileartifactid-version.jar -DgroupIdgroupid -DartifactIdartifactid -Dversionversion -Dpackagingjar -DlocalRepositoryPath. -DcreateChecksumtrue参数解释 在上述命令中,需要替换以下参数: artifactid-vers…

计算机组成原理课程设计 报告

在我的博客查看:https://chenhaotian.top/study/computer-composition-principles-course-design/ 计算机组成原理课程设计 报告 一、目的和要求 深入了解计算机各种指令的执行过程,以及控制器的组成,指令系统微程序设计的具体知识&#xf…

【前端知识】React 基础巩固(二十六)——Portals 的使用

React 基础巩固(二十六)——Portals 的使用 Portals 通常&#xff0c;组件会渲染到 root 节点下。可使用 Portals 将组件渲染至其他节点。 添加 id 为 more、modal 的 div 元素 <div id"root"></div> <div id"more"></div> &l…

工作:三菱PLC之CC-Link IE Field Network通讯知识及应用

工作&#xff1a;三菱PLC之CC-Link IE Field Network通讯知识及应用 一、理论 1. 简介连接 CC-LINK-IE通讯分别有 CC-Link IE TSN&#xff0c;CC-Link IE Control Network&#xff0c;CC-Link IE Field Network&#xff0c;CC-Link IE Field Network Basic几种形式&#xff…

成功解决wget下载报错 : wget HTTP request sent, awaiting response... 403 Forbidden

成功解决wget下载报错 : wget HTTP request sent, awaiting response... 403 Forbidden 问题描述解决方案原理什么是User Agent解决 问题描述 –2023-07-15 02:32:57-- https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-2023.03-Linux-x86_64.sh Resolving mi…

PyTorch: 池化-线性-激活函数层

文章和代码已经归档至【Github仓库&#xff1a;https://github.com/timerring/dive-into-AI 】或者公众号【AIShareLab】回复 pytorch教程 也可获取。 文章目录 nn网络层-池化-线性-激活函数层池化层最大池化&#xff1a;nn.MaxPool2d()nn.AvgPool2d()nn.MaxUnpool2d()线性层激…

linux 下如何安装 tar.gz包

linux 下如何安装 tar.gz包 解压缩进入解压后的文件目录下 解压缩 tar -zxvf pycharm-community-2023.1.3.tar.gz进入解压后的文件目录下 ./pycharm.sh可执行Pycharm 建议将目录转移到其他位置 我习惯使用2020版本的 下载地址

源码阅读: echo 回显程序

文章目录 1. 目的2. 原始代码3. 化简和跨平台支持4. 修改后代码的代码分析5. References 1. 目的 阅读 netbsd 9.3 的 echo.c, 练习 C 语言源码阅读的技能。 2. 原始代码 https://github.com/NetBSD/src/blob/trunk/bin/echo/echo.c /* $NetBSD: echo.c,v 1.23 2021/11/16 …

2023年Java最新面试题

由【后端面试题宝典】提供 和 equals 的区别是什么&#xff1f; 对于基本类型&#xff0c;比较的是值&#xff1b;对于引用类型&#xff0c;比较的是地址&#xff1b;equals不能用于基本类型的比较&#xff1b;如果没有重写equals&#xff0c;equals就相当于&#xff1b;如果重…

基于JavaSwing+Mysql的仓库销售管理系统

点击以下链接获取源码&#xff1a; https://download.csdn.net/download/qq_64505944/88049275 JDK1.8 MySQL5.7 功能&#xff1a;管理员与员工两个角色登录&#xff0c;基础数据查找&#xff0c;仓库查找&#xff0c;增删改查仓库信息、商品等 源码数据库文件配置文件课程设…

5分钟构建电商API接口服务 | python小知识

1. 什么是API 我们经常会使用一些API接口来完成特定的功能&#xff0c;比如查询天气的数据&#xff0c;下载股票的数据&#xff0c;亦或是调用ChatGPT模型的结构等等。 API全称是Application Programming Interface&#xff0c;即应用程序接口&#xff0c;它通常提供了一个功…

Mysql单表多表查询练习

题目要求&#xff1a; 1.查询student表的所有记录 2.查询student表的第2到4条记录 3.从student表查询所有的学生的学号&#xff08;id&#xff09;&#xff0c;姓名&#xff08;name&#xff09;&#xff0c;和院系&#xff08;department&#xff09;的信息 4.从student表…

SpringAMQP - 消息传输时,如何提高性能?解决 SQL 注入问题?

目录 一、问题背景 二、从消息转化器根源解决问题 1.引入依赖 2.在服务生产者和消费者中都重新定义一个 MessageConverter&#xff0c;注入到 Spring 容器中 一、问题背景 在SpringAMQP的发送方法中&#xff0c;接收消息的类型是Object&#xff0c;也就是说我们可以发送任意…