Mnist分类与气温预测任务

news2024/9/28 9:31:50

目录

  • 传统机器学习与深度学习的特征工程
  • 特征向量
  • pytorch实现minist代码解析
  • 归一化
  • 损失函数
  • 计算图
  • Mnist分类
    • 获取Mnist数据集,预处理,输出一张图像
    • 面向工具包编程
    • 使用TensorDataset和DataLoader来简化数据预处理
    • 计算验证集准确率
  • 气温预测
    • 回归
    • 构建神经网络
    • 调包
    • 预测训练结果
    • 画图对比

传统机器学习与深度学习的特征工程

在这里插入图片描述
在这里插入图片描述
卷积层:原始输入中间提取有用的一个局部特征
激活函数:用于增加模型的一些非线性,可以让模型学习更加复杂模式
池化层:用于减少数据的维度

特征向量

在这里插入图片描述

pytorch实现minist代码解析

在这里插入图片描述

首先继承nn.Module类的一个子类ConvNetsuper方法就是在调用nn.Module的一个__init__方法,确保__init__方法中定义的属性和方法都可以在ConvNet中使用

归一化

在这里插入图片描述
在这里插入图片描述

损失函数

在这里插入图片描述

计算图

在这里插入图片描述

Mnist分类

获取Mnist数据集,预处理,输出一张图像

import torch
print(torch.__version__)
#win用户
DEVICE=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#mac用户
DEVICE=torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
print('当前设备',DEVICE)

在这里插入图片描述

#将图像嵌入输出的单元格
%matplotlib inline
from pathlib import Path # 处理文件路径
import requests

DATA_PATH = Path("data") 
PATH = DATA_PATH / "mnist"
PATH.mkdir(parents=True, exist_ok=True)

URL = "http://deeplearning.net/data/mnist/"
FILENAME = "mnist.pkl.gz"

if not (PATH / FILENAME).exists():
    content = requests.get(URL + FILENAME).content
    (PATH / FILENAME).open("wb").write(content)
import pickle
import gzip

with gzip.open((PATH / FILENAME).as_posix(), "rb") as f:
    ((x_train, y_train), (x_valid, y_valid), (x_test, y_test)) = pickle.load(f, encoding="latin-1")
print("x_train: ", type(x_train), x_train.dtype, x_train.size, x_train.shape, "; y_train: ", y_train.shape)

在这里插入图片描述

print("x_valid: ", type(x_valid), x_valid.dtype, x_valid.size, x_valid.shape, "; y_valid: ", y_valid.shape)

在这里插入图片描述

from matplotlib import pyplot

pyplot.imshow(x_train[2].reshape((28, 28)), cmap="gray")

在这里插入图片描述

y_train[:10]

在这里插入图片描述

x_train, y_train, x_valid, y_valid = map(
    lambda x: torch.tensor(x, device=DEVICE),
    (x_train, y_train, x_valid, y_valid)
)
print("x_train: ", x_train, "; y_train: ", y_train)
x_train[0]
import torch.nn.functional as F

loss_func = F.cross_entropy # 损失函数,传入预测、真实值的标签

def model(xb):
    xb = xb.to(DEVICE)
    return xb.mm(weights) + bias  # x*w+b
bs = 64

xb = x_train[0:bs] # 64, 784

yb = y_train[0:bs] # 真实标签

weights = torch.randn([784, 10], dtype = torch.float, requires_grad = True)

bias = torch.zeros(10, requires_grad = True)

weights = weights.to(DEVICE)
bias = bias.to(DEVICE)

print(loss_func(model(xb), yb))

在这里插入图片描述

补充:关于map函数的例子

def square(x):
    return x**2
numbers=[1,2,3,4,5]
squares=map(square,numbers)
print(list(squares))

在这里插入图片描述
也就是map函数第一个参数是函数,第二个参数是数值,将函数作用于数值

面向工具包编程

from torch import nn # 提供神经网网络的类和函数 ,nn.Module

class Mnist_NN(nn.Module):
    def __init__(self): # 设计房屋图纸
        super(Mnist_NN, self).__init__()
        self.hidden1 = nn.Linear(784, 256) # 784-输入层,256-隐藏层1
        self.hidden2 = nn.Linear(256, 128)
        self.out = nn.Linear(128, 10)
    def forward(self, x): # 实际造房子
        x2 = F.relu(self.hidden1(x)) # x: [bs, 784], w1: [784, 256], b1: [256] -> x2:[bs,256]
        x3 = F.relu(self.hidden2(x2)) # x2: [bs, 256], w2:[256, 128], b2[128] -> x3[bs, 128]
        x_out = self.out(x3) # x3: [bs, 128], w3: [128, 10], b3[10] -> x_out: [bs, 10]
        
        return x_out
net = Mnist_NN().to(DEVICE)
print(net)

在这里插入图片描述

print(net.hidden1.weight)

在这里插入图片描述

for name, parameter in net.named_parameters():
    print(name, parameter)

使用TensorDataset和DataLoader来简化数据预处理

from torch.utils.data import TensorDataset

from torch.utils.data import DataLoader

 
train_ds = TensorDataset(x_train, y_train) #torch.utils.data.Dataset
train_dl = DataLoader(train_ds, batch_size=64, shuffle=True)

valid_ds = TensorDataset(x_valid, y_valid)
valid_dl = DataLoader(valid_ds, batch_size=bs)
data_iter = iter(train_dl)

batch_x, batch_y = next(data_iter)
print(batch_x.shape, batch_y.shape)
print(batch_y)

在这里插入图片描述

batch_x, batch_y = next(data_iter)
print(batch_x.shape, batch_y.shape)
print(batch_y)

在这里插入图片描述

def get_data(train_bs, valid_bs, bs): # 创建数据加载器
    return (
        DataLoader(train_ds, batch_size=bs, shuffle=True),
        DataLoader(valid_ds, batch_size=bs)
    )
from torch import optim
def get_model():
    model = Mnist_NN().to(DEVICE)
    optimizer = optim.SGD(model.parameters(), lr=0.01) # model.parameters()包含了所有的权重和偏执参数
    return model, optimizer

注:adam相比于SGD是引入了一个惯性,相当于一个平行四边形的一个合成法则
在这里插入图片描述

def loss_batch(model, loss_func, xb, yb, opt=None):
    loss = loss_func(model(xb), yb)
    
    if opt is not None: # 此时是训练集
        
        opt.zero_grad()
        loss.backward()
        opt.step()
        
    return loss.item(), len(xb)

opt为True是训练集测试损失,opt为None是验证集测试损失

def loss_batch(model, loss_func, xb, yb, opt=None):
    loss = loss_func(model(xb), yb)
    
    if opt is not None: # 此时是训练集
        
        opt.zero_grad()
        loss.backward()
        opt.step()
        
    return loss.item(), len(xb)
import numpy as np

def fit(epoch, model, loss_func, opt, train_dl, valid_dl):
    for step in range(epoch):
        model.train()
        for xb, yb in train_dl:
            loss_batch(model, loss_func, xb, yb, opt)
        
        model.eval() # 考试
        with torch.no_grad():
            
            losses, nums = zip(
                *[loss_batch(model, loss_func, xb, yb) for xb, yb in valid_dl] # "*"——解包/解开
            )
            # print(f"losses: {losses}")
            # print(f"nums: {nums}")
            
        val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums) # 加权平均损失
        print('当前step: '+str(step), '验证集损失: '+str(val_loss))
train_dl, valid_dl = get_data(train_ds, valid_ds, bs=64)
model, optimizer = get_model()
fit(30, model, loss_func, optimizer, train_dl, valid_dl)

在这里插入图片描述

计算验证集准确率

torch.set_printoptions(precision=4, sci_mode=False)
for xb, yb in valid_dl:
    output = model(xb)
    print(output)
    print(output.shape)
    break
for xb, yb in valid_dl:
    output = model(xb)
    probs = torch.softmax(output, dim=1)
    print(probs)
    print(probs.shape)
    break
for xb, yb in valid_dl:
    output = model(xb)
    probs = torch.softmax(output, dim=1)
    preds = torch.argmax(probs, dim=1)
    print(preds)
    print(preds.shape)
    break
correct_predict = 0 # 计数正确预测图片的数目
total_quantity = 0 # 计数验证集总数

for xb, yb in valid_dl:
    output = model(xb)
    probs = torch.softmax(output, dim=1)
    preds = torch.argmax(probs, dim=1)
    total_quantity += yb.size(0)
    # print(yb.size(0))
    # print((preds == yb).sum())
    # print((preds == yb).sum().item())
    correct_predict += (preds == yb).sum().item()

print(f"验证集的准确率是: {100 * correct_predict / total_quantity} % ")

在这里插入图片描述

气温预测

回归

import numpy as np # 矩阵运算
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.optim as optim

import warnings
warnings.filterwarnings("ignore")

%matplotlib inline
features = pd.read_csv('temps.csv')

features.head()

在这里插入图片描述

print("数据维度: ", features.shape)

在这里插入图片描述

# 处理时间数据
import datetime

years = features['year']
months = features['month']
days = features['day']

dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates[:5]

在这里插入图片描述

dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
dates[:5]

在这里插入图片描述

plt.style.use('fivethirtyeight')

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (10, 10))
fig.autofmt_xdate(rotation=45) #x轴翻转45度

# 标签值
ax1.plot(dates, features['actual'])
ax1.set_xlabel(''); ax1.set_ylabel('Temoerature'); ax1.set_title('Actual Max Temp')

# 昨天温度
ax2.plot(dates, features['temp_1'])
ax2.set_xlabel(''); ax2.set_ylabel('Temoerature'); ax2.set_title('Previous Max Temp')

# 前天温度
ax3.plot(dates, features['temp_2'])
ax3.set_xlabel('Date'); ax3.set_ylabel('Temoerature'); ax3.set_title('Two Days Prior Max Temp')

# 朋友预测温度
ax4.plot(dates, features['friend'])
ax4.set_xlabel('Date'); ax4.set_ylabel('Temoerature'); ax4.set_title('Friend Max Temp')

在这里插入图片描述
在这里插入图片描述

features = pd.get_dummies(features)
features.head()

在这里插入图片描述

labels = np.array(features['actual'])

# 在特征中去掉标签
features = features.drop('actual', axis=1)

feature_list = list(features.columns)

features = np.array(features)
features.shape

在这里插入图片描述

from sklearn import preprocessing
input_features = preprocessing.StandardScaler().fit_transform(features)
input_features[:5]

构建神经网络

x = torch.tensor(input_features, dtype = float)
y = torch.tensor(labels, dtype=float)
print(x.shape, y.shape)
# 权重初始化
weights = torch.randn((14, 128), dtype = float, requires_grad = True) 
biases = torch.randn(128, dtype = float, requires_grad = True) 
weights2 = torch.randn((128, 1), dtype = float, requires_grad = True) 
biases2 = torch.randn(1, dtype = float, requires_grad = True) 


learning_rate = 0.001
losses = []

for i in range(1000):
    
    hidden = x.mm(weights) + biases
    
    hidden = torch.relu(hidden)
    
    predictions = hidden.mm(weights2) + biases2
    
    loss = torch.mean((predictions - y)**2)
    losses.append(loss.item())
    
    if i % 100 == 0:
        print(f"loss: {loss}")
    
    # 反向传播
    loss.backward()
    
    # 更新,相当于optim.step()
    weights.data.add_(- learning_rate * weights.grad.data)  
    biases.data.add_(- learning_rate * biases.grad.data)
    weights2.data.add_(- learning_rate * weights2.grad.data)
    biases2.data.add_(- learning_rate * biases2.grad.data)
        
    # 清空梯度,optim.zero_grad()
    weights.grad.data.zero_()
    biases.grad.data.zero_()
    weights2.grad.data.zero_()
    biases2.grad.data.zero_()

在这里插入图片描述

调包

import torch.optim as optim

# 数据准备
# 将数据都转化为tensor张量
x = torch.tensor(input_features, dtype = torch.float)
y = torch.tensor(labels, dtype=torch.float).view(-1, 1) # 改成(n, 1)
print(x.shape, y.shape)
model = torch.nn.Sequential(
    torch.nn.Linear(14, 128),
    torch.nn.ReLU(),
    torch.nn.Linear(128, 1)
)

# 均方误差MSE
criterion = torch.nn.MSELoss(reduction='mean')

optimizer = optim.Adam(model.parameters(), lr=0.001)


losses = [] # 存储每一次迭代的损失

for i in range(3000):
    predictions = model(x) # [348, 1]
    
    loss = criterion(predictions, y)
    losses.append(loss.item())
    if i % 200 == 0:
        print(f"loss: {loss.item()}")
        
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

在这里插入图片描述

预测训练结果

x = torch.tensor(input_features, dtype = torch.float)
predict = model(x).data.numpy()
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]

# 创建一个表格来存日期和对应的真实标签
true_data = pd.DataFrame(data = {'date': dates, 'actual': labels})

# 创建一个表格来存日期和对应的预测值
predictions_data = pd.DataFrame(data = {'date': dates, 'prediction': predict.reshape(-1)})

predict.shape, predict.reshape(-1).shape

在这里插入图片描述

true_data[:5]

在这里插入图片描述

predictions_data[:5]

在这里插入图片描述

画图对比

# 真实值
plt.plot(true_data['date'], true_data['actual'], 'b-', label = "actual")

# 预测值
plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = "prediction")

plt.xticks(rotation = 60)

plt.legend()

在这里插入图片描述

# 真实值
plt.plot(true_data['date'], true_data['actual'], 'b-', label = "actual")

# 预测值
plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = "prediction")

plt.xticks(rotation = 60)

plt.legend()

plt.xlabel('Date'); plt.ylabel('Maximum Tempurate(F)'); plt.title('Actual and Predicted Values')

在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

网页版五子棋项目演示

项目源码:五子棋游戏 演示使用的用户名:zyz 密码:123 注册页面: 登录页面: 游戏大厅页面: 未匹配: 匹配中: 游戏房间页面: 对方落子: 己方落子: 对…

5.6 Java递归讲解

5.6 Java递归讲解 A方法调用B方法,我们很容易理解递归就是:A方法调用A方法!就是自己调用自己利用递归可以实现通过简单的程序来解决一些复杂的问题。它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解&#xff0…

Redis的五大数据类型介绍

、简介 Redis的五大数据类型也称五大数据对象;前面介绍过6大数据结构,Redis并没有直接使用这些结构来实现键值对数据库,而是使用这些结构构建了一个对象系统redisObject;这个对象系统包含了五大数据对象,字符串对象&am…

MFC第二十四天 使用GDI对象画笔和画刷来开发控件(分页控件选择态的算法分析、使用CToolTipCtrl开发动静态提示)

文章目录 GDI对象画笔和画刷来开发控件梯形边框的按钮控件CMainDlg.hCMainDlg.cppCLadderCtrl.hCLadderCtrl.cpp 矩形边框的三态按钮控件 CToolTipCtrl开发动静态提示CMainDlg.hCMainDlg.cppCLadderCtrl.hCLadderCtrl.cpp: 实现文件 矩形边框的三态按钮控件 CToolTipCtrl开发动…

linux服务器安装redis

一、安装下载 下载安装参考文章 下载安装包地址:https://download.redis.io/releases/ 亲测有效,但是启动的步骤有一些问题 安装完成!!! 二、启动 有三种启动方式 默认启动指定配置启动开机自启 说明&#xff1a…

CentOS下 Docker、Docker Compose 的安装教程

Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口。 Docker Compose是用于定义…

【Lua学习笔记】Lua进阶——Table(4)继承,封装,多态

文章目录 封装继承多态 封装 // 定义基类 Object {}//由于表的特性,该句就相当于定义基类变量 Object.id 1//该句相当于定义方法,Object可以视为定义的对象,Test可以视为方法名 //我们知道Object是一个表,但是抽象地看&#xff…

为什么要有虚拟内存?

操作系统是通过内存分段和内存分页的方式管理虚拟内存地址和物理内存地址之间的关系 内存分段 程序是由若干个逻辑分段组成的,代码分段、数据分段、栈段、堆段组成,不同的段有不同的属性,所以就用分段的形式分离开。 分段机制下的虚拟内存…

【业务功能篇58】Springboot + Spring Security 权限管理 【下篇】

4.2.2.3 SpringSecurity工作流程分析 SpringSecurity的原理其实就是一个过滤器链,内部包含了提供各种功能的过滤器。这里我们可以看看入门案例中的过滤器。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KjoRRost-1690534711077)(http…

使用Django自带的后台管理系统进行数据库管理的实例

Django自带的后台管理系统主要用来对数据库进行操作和管理。它是Django框架的一个强大功能,可以让你快速创建一个管理界面,用于管理你的应用程序的数据模型。 使用Django后台管理系统,你可以轻松地进行以下操作: 数据库管理&…

详解机器学习中的熵、条件熵、相对熵和交叉熵

这个是讲的不错的链接 https://www.cnblogs.com/kyrieng/p/8694705.html 这个是交叉熵 https://blog.csdn.net/m0_57236802/article/details/129554878

《焊接点云处理》-角焊焊缝处理

角焊缝点云处理 前言一、代码二、实现步骤3、验证前言 针对T型板,识别效果如下所示 一、代码 主函数 #include "CGALRECONSTRUCT.h" #include "CGALREGIONPLANE.h" #include

设计利器,掌握CAD辅助命令的必备指南

CAD设计中的辅助命令是提高效率和确度的关键工具。掌握并正确运用CAD中的各种辅助命令对于设计师们来说至关重要。本文将为你详细介绍如何使用CAD中的辅助命令,从而帮助你在设计过程中更加高效地实现你的创意。、 大家有没有发现,当我们的直线命令移动到…

Rethinking the Image Fusion(PMGI)

1.摘要 本文提出了一种基于梯度和强度比例维护(PMGI)的快速统一图像融合网络,可以端到端实现各种图像融合任务,包括红外和可见图像融合、多曝光图像融合、医学图像融合、多焦点图像融合和全色增强。我们将图像融合问题统一为源图…

C++信号量与共享内存实现进程间通信

关于信号量和共享内存的相关知识可参考下面链接: 进程间通信方式介绍_夜雨听萧瑟的博客-CSDN博客 C 创建共享内存_c共享内存_夜雨听萧瑟的博客-CSDN博客 信号量SytemV与Posix信号量的介绍与用法_夜雨听萧瑟的博客-CSDN博客 直接上代码,代码如下&#…

蓝桥杯单片机第十二届国赛 真题+代码

iic.c /* # I2C代码片段说明1. 本文件夹中提供的驱动代码供参赛选手完成程序设计参考。2. 参赛选手可以自行编写相关代码或以该代码为基础&#xff0c;根据所选单片机类型、运行速度和试题中对单片机时钟频率的要求&#xff0c;进行代码调试和修改。 */ #include <STC1…

golang文件锁,目录锁,syscall包的使用

先说结论 1. golang提供了syscall包来实现文件/目录的加锁&#xff0c;解锁 2. syscall包属于文件锁&#xff0c;是比较底层的技术&#xff0c;并不能在所有操作系统上完全实现&#xff0c;linux上实现了&#xff0c;windows下面就没有 3. 加锁时调用syscall.Flock(fd&#…

安全学习DAY09_加密逆向,特征识别

算法逆向&加密算法分类&#xff0c;特征识别 文章目录 算法逆向&加密算法分类&#xff0c;特征识别算法概念&#xff0c;分类单向散列加密 - MD5对称加密 - AES非对称加密 - RSA 常见加密算法识别特征&#xff0c;解密特点MD5密文特点BASE64编码特点AES、DES特点RSA密文…

leaftjs实现全国温度降水气压风速等值面风场洋流效果

实现内容 数据爬取、地图marker聚合、鼠标移动显示pop&#xff0c;风场&#xff0c;洋流&#xff0c;温度等值面、降水等值面、气压等值面、风速等值面&#xff0c;洋流方向、洋流流速展示、风场方向、风场风速展示&#xff0c;后期扩展小时预报&#xff0c;分钟预报、7天预报…