一、实验目的及要求
1. 掌握Python语言的编程方法和基于Tensor的人工智能编程方法
2. 熟悉图像相关的数据集,如iris数据集,Mnist手写数字数据集、CIFAR10目标识别数据集
3. 掌握多层感知器模型和CNN模型的特性
4. 掌握建模的流程、对模型结果的分析及优化
二、实验设备(环境)及要求
Anaconda、Jupyter Notebook、pandas、pytorch。
三、实验内容与步骤
1. 搭建pytorch环境
(1)安装Anaconda
(2)配置conda的国内镜像源
(3)创建pytorch虚拟环境
(4)在虚拟环境中安装pytorch
2. pytorch的基本用法
1)
PyTorch的列表、张量和数组的转换
import torch
import numpy as np
# 1. 列表转张量
list_data = [1, 2, 3, 4]
tensor_from_list = torch.tensor(list_data)
print("张量(Tensor)从列表创建:", tensor_from_list)
# 2. 张量转列表
tensor_to_list = tensor_from_list.tolist()
print("列表(List)从张量转换:", tensor_to_list)
# 3. NumPy数组转张量
numpy_array = np.array([1, 2, 3, 4])
tensor_from_numpy = torch.from_numpy(numpy_array)
print("张量(Tensor)从NumPy数组创建:", tensor_from_numpy)
# 4. 张量转NumPy数组
numpy_back = tensor_from_numpy.numpy()
print("NumPy数组(ndarray)从张量转换:", numpy_back)
运行截图:
PyTorch张量切片机view()方法:
import torch
# 假设有一个形状为 (3, 4) 的张量
tensor = torch.randn(3, 4)
# 使用 `.view()` 方法将其形状改为 (2, 6)
reshaped_tensor = tensor.view(2, 6)
print("原始张量的形状:", tensor.shape)
print("调整后张量的形状:", reshaped_tensor.shape)
运行截图:
PyTorch张量求梯度:
import torch
# 创建一个可训练的浮点数张量,设置requires_grad=True来跟踪计算历史
x = torch.tensor([1., 2., 3., 4.], requires_grad=True)
print("张量(Tensor):", x)
# 执行一个数学运算
y = x.pow(2) # 求张量的平方
print("平方结果:", y)
# 计算一个标量损失值,这里简单地取y的和作为示例
loss = y.sum() # 实际场景中应使用适当的损失函数
print("损失值(Loss):", loss)
# 应用 backward() 到损失值上
loss.backward()
# 访问张量 x 的梯度
grad_x = x.grad
print("张量 x 的梯度(即对损失求导):", grad_x)
运行截图:
PyTorch的矩阵压缩和扩张:
import torch
# 创建一个2x3的随机矩阵
matrix = torch.randn(2, 3)
print("原始矩阵:", matrix)
# 矩阵压缩(扁平化)
flattened_matrix = matrix.view(-1)
print("压缩后的张量:", flattened_matrix)
# 矩阵扩张(增加维度)
expanded_matrix = flattened_matrix.unsqueeze(0)
print("扩张后的张量:", expanded_matrix)
运行截图:
2)
用 Python 实现购买2个苹果和3个橙子,苹果单价为100,橙子单价为150,消费税为10%,要求输出每个计算节点的结果:a、苹果和橙子的总价(含消费税),b、苹果数量,苹果单价,橙子单价,橙子数量和消费税这五个参数的反向传播值。
import torch
# 定义变量,并设置requires_grad=True以追踪计算历史
apple_count = torch.tensor(2., requires_grad=True)
apple_price = torch.tensor(100., requires_grad=True)
orange_count = torch.tensor(3., requires_grad=True)
orange_price = torch.tensor(150., requires_grad=True)
tax_rate = torch.tensor(0.10, requires_grad=True)
# 计算苹果和橙子的总价
apple_total = apple_count * apple_price
orange_total = orange_count * orange_price
subtotal = apple_total + orange_total
total_with_tax = subtotal * (1 + tax_rate)
# 输出每个计算节点的结果
print("苹果总价(不含税):", apple_total.item())
print("橙子总价(不含税):", orange_total.item())
print("总价(含消费税):", total_with_tax.item())
# 进行反向传播计算梯度
total_with_tax.backward()
# 输出各参数的梯度(反向传播值)
print("\n反向传播值:")
print(f"苹果数量的梯度:{apple_count.grad.item()}")
print(f"苹果单价的梯度:{apple_price.grad.item()}")
print(f"橙子数量的梯度:{orange_count.grad.item()}")
print(f"橙子单价的梯度:{orange_price.grad.item()}")
print(f"消费税率的梯度:{tax_rate.grad.item()}")
运行截图: