9.16 日总结

leetcode850

题目描述:

我们给出了一个(轴对齐的)二维矩形列表 rectangles 。 对于 rectangle[i] = [x1, y1, x2, y2],其中(x1,y1)是矩形 i 左下角的坐标, (xi1, yi1) 是该矩形 左下角 的坐标, (xi2, yi2) 是该矩形 右上角 的坐标。

计算平面中所有 rectangles 所覆盖的 总面积 。任何被两个或多个矩形覆盖的区域应只计算 一次 。

返回 总面积 。因为答案可能太大,返回 109 + 7 的 模 。

PS:昨天李沐老师的课内容过于丰富,导致看完后没有时间总结,今天争取看懂代码记录下总结。
 

每次碰到困难题基本上都要求助于评论区的思路,本题是参考了宫水三叶的解题思路后用C++改写的,由于C++stl库还不是很熟悉,也参考了一部分其他人的C++代码。不知道什么时候自己能够独立解出一道hard。

本题思路其实并不难,只是对我这种新手很难想到。可以理解为把所有矩形按列拆分成n*1的矩阵,我们所需要求得就是n,这其中的1可以是其他长度,根据给定的矩形而定。我们首先将rec中的所有x轴元素push到向量中,按从小到大的顺序排序,找出n*1中的1。然后,遍历所有矩形,如果该横坐标区间属于某个矩形,就将该矩形的纵坐标以成对的形式放入向量中,为什么要成对,因为这代表了上下界,如果不成对,在所有y方向都连续无空缺的情况下不会出错,但是一旦有空缺就会多算。最后计算矩形面积相加得到答案。代码如下。

class Solution {
public:
    int rectangleArea(vector<vector<int>>& rectangles) {
        vector<int> xaxis; //存储x轴值

        //将x轴坐标载入
        for(vector<int>& v : rectangles) { 
            xaxis.push_back(v[0]);
            xaxis.push_back(v[2]);
        }

        //对x轴坐标进行排序
        sort(xaxis.begin(), xaxis.end());
        int res = 0; 

        //遍历xaxis所有的坐标,找出每个相邻坐标之间的y方向的长度
        for(int i = 1; i < xaxis.size(); ++i) {
            int a = xaxis[i-1], b = xaxis[i];
            int len = b-a;
            if(len == 0)
                continue;
            vector<pair<int, int>> yaxis;
            for(vector<int>& v : rectangles) {
                if(a >= v[0] && b <= v[2])
                    yaxis.push_back({v[1], v[3]});
            }
            sort(yaxis.begin(), yaxis.end());

            //计算y方向长度
            int l = -1, r = -1;
            long long ans = 0;
            for(pair<int, int>& v : yaxis) {
                if(v.first > r) {
                    ans += r - l;
                    l = v.first;
                    r = v.second;
                } else if(v.second > r) {
                    r = v.second;
                }                
            }
            ans += r - l;
            ans %= (long long)1e9+7;
            ans *= len;
            ans %= (long long)1e9+7;
            res += ans;
            res %= (long long)1e9+7;
        }
        return res;
    }
};

跟李沐学pytorch

这是昨天啃剩下的,今天又仔细读了一遍代码,顺带做了点注释,对代码里面的很多函数还是不是很了解,尤其是矩阵的大小上一直在纠结,最后发现与其自己瞎琢磨,不如输出一遍。

详细实现softmax在mnist数据集上的分类任务的步骤如下:一,首先进行数据的读取,利用DataLoader进行,返回训练集和测试集的迭代器。二,二维图像或三维图像不好处理,将其flatten为一维。三,分别根据定义写出sotfmax函数、网络预测函数(即前向通路,与权重偏置做积)、交叉熵函数、正确率计算函数、正确率评价函数。四,训练函数,主要是用何种方法进行梯度更新。最后如果需要看效果的话test测试集一下,画图输出。

from urllib import request
import torch
from IPython import display
from d2l import torch as d2l

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

#print(type(train_iter))  #<class 'torch.utils.data.dataloader.DataLoader'>

num_inputs = 784 # 28*28 flatten 操作
num_outputs = 10 # classes

w = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
b = torch.zeros(num_outputs, requires_grad = True)  #生成0的数组 1*10
# print(b)

def softmax(x):
    x_exp = torch.exp(x)                    
    partition = x_exp.sum(1, keepdim=True)  #除去列维度, 相当于把所有预测概率的指数形式求和
    return x_exp / partition   #广播机制 自动扩展

# X = torch.normal(0, 1, (2, 5))
# X_prob = softmax(X)
# print(X_prob, X_prob.sum(1))

#实现softmax回归模型

def net(x):
    return softmax(torch.matmul(x.reshape((-1, w.shape[0])), w) + b) #根据线性关系预测


#交叉熵损失
# y = torch.tensor([0, 2])
# y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
# y_hat[[0, 1], y]

def cross_entropy(y_hat, y):
    return -torch.log(y_hat[range(len(y_hat)), y])          #交叉熵损失函数H(p,q) = -sigima(p * log q) range找出有多少样本 y代表真实值

# print(cross_entropy(y_hat, y))

def accuracy(y_hat, y):
    '''计算正确的数量'''
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        y_hat = y_hat.argmax(axis = 1)          #axis代表坐标轴 0是纵轴, 1是横轴
    cmp = y_hat.type(y.dtype) == y              #cmp返回bool类型矩阵,列表?
    return float(cmp.type(y.dtype).sum())

# print(accuracy(y_hat, y) / len(y))

def evaluate_accuracy(net, data_iter):          #评价正确性
    if isinstance(net, torch.nn.Module):        #判断net是否为torch.nn.Module的一个实例,是true
        net.eval()                              #计算正确率的时候是评价,不进行normalazition和dropout
    metric = Accumulator(2)                     
    for x, y in data_iter:
        metric.add(accuracy(net(x), y), y.numel())  #numel返回元素中的个数
    return metric[0] / metric[1]


class Accumulator:  #@save
    """在n个变量上累加"""
    def __init__(self, n):
        self.data = [0.0] * n                   #把0复制n次变成一个新的数组

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]
                    # #zip后返回一个对象
                    # a = [1, 2, 3]
                    # b = ["a", "b", "c"]
                    # zip(a, b)  # 返回的是一个对象
                    # list(zip(a, b))  # 输出为:[(1, 'a'), (2, 'b'), (3, 'c')]
    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]

# if __name__ == "__main__":
#     print(evaluate_accuracy(net, test_iter))

def train_epoch_ch3(net, train_iter, loss, updater):  #@save
    """训练模型一个迭代周期(定义见第3章)"""
    # 将模型设置为训练模式
    if isinstance(net, torch.nn.Module):
        net.train()
    # 训练损失总和、训练准确度总和、样本数
    metric = Accumulator(3)
    for X, y in train_iter:
        # 计算梯度并更新参数
        y_hat = net(X)
        l = loss(y_hat, y)
        if isinstance(updater, torch.optim.Optimizer):
            # 使用PyTorch内置的优化器和损失函数
            updater.zero_grad()
            l.mean().backward()
            updater.step()
        else:
            # 使用定制的优化器和损失函数
            l.sum().backward()
            updater(X.shape[0])
        metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
    # 返回训练损失和训练精度
    return metric[0] / metric[2], metric[1] / metric[2]


class Animator:  #@save
    """在动画中绘制数据"""
    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
                 ylim=None, xscale='linear', yscale='linear',
                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
                 figsize=(3.5, 2.5)):
        # 增量地绘制多条线
        if legend is None:
            legend = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        # 使用lambda函数捕获参数
        self.config_axes = lambda: d2l.set_axes(
            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        # 向图表中添加多个数据点
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()
        display.display(self.fig)
        d2l.plt.draw()
        d2l.plt.pause(0.001)
        display.clear_output(wait=True)

def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):  #@save
    """训练模型(定义见第3章)"""
    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
                        legend=['train loss', 'train acc', 'test acc'])
    for epoch in range(num_epochs):
        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
        test_acc = evaluate_accuracy(net, test_iter)
        animator.add(epoch + 1, train_metrics + (test_acc,))
    train_loss, train_acc = train_metrics

    assert train_loss < 0.5, train_loss
    assert train_acc <= 1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc           #限定范围

lr = 0.1

def updater(batch_size):
    return d2l.sgd([w, b], lr, batch_size)

num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)

def predict_ch3(net, test_iter, n=6):  #@save
    """预测标签(定义见第3章)"""
    for X, y in test_iter:
        break
    trues = d2l.get_fashion_mnist_labels(y)
    preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1))
    titles = [true +'\n' + pred for true, pred in zip(trues, preds)]
    d2l.show_images(
        X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])
    d2l.plt.show()

predict_ch3(net, test_iter)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值