def _normalize_idx(self, idx): nidx = idx if nidx < 0: nidx += len(self) if nidx < 0: nidx = 0 return nidx def __getitem__(self, idx): """Implements `x = self[idx]`""" assert(isinstance(idx, int)) nidx = self._normalize_idx(idx) if nidx >= self.length: raise IndexError else: #start at head, skip the NONE sentinel, now at index 0, while loop to walk to nidx, return data # or figure out closer to head or head.prior(tail), make the walk shorter if idx< (self.length/2): #start at head.next, walk forward idx number of nodes current=self.head.next count=0 while count<nidx: current=current.next count+=1 else: #start at head.prior, walk backward len(self.data)-idx-1 number of nodes current=self.head.prior count=self.length-1 while count>nidx: current=current.prior count-=1 return current.val 改写代码风格并保持变量名,代码意思不变

时间: 2024-01-12 21:05:45 浏览: 118
下面是改写后的代码风格: ``` def _normalize_idx(self, idx): nidx = idx if nidx < 0: nidx += len(self) if nidx < 0: nidx = 0 return nidx def __getitem__(self, idx): """Implements `x = self[idx]`""" assert(isinstance(idx, int)) nidx = self._normalize_idx(idx) if nidx >= self.length: raise IndexError else: # Start at head, skip the NONE sentinel, now at index 0, while loop to walk to nidx, return data # Or figure out closer to head or head.prior(tail), make the walk shorter if idx < (self.length/2): # Start at head.next, walk forward idx number of nodes current = self.head.next count = 0 while count < nidx: current = current.next count += 1 else: # Start at head.prior, walk backward len(self.data)-idx-1 number of nodes current = self.head.prior count = self.length-1 while count > nidx: current = current.prior count -= 1 return current.val ``` 注意,变量名没有改变,只是对代码进行了一些格式化和注释。

相关推荐

X_train,T_train=idx2numpy.convert_from_file('emnist/emnist-letters-train-images-idx3-ubyte'),idx2numpy.convert_from_file('emnist/emnist-letters-train-labels-idx1-ubyte')转化为相同形式train_num = 60000 test_num = 10000 img_dim = (1, 28, 28) img_size = 784 def _download(file_name): file_path = dataset_dir + "/" + file_name if os.path.exists(file_path): return print("Downloading " + file_name + " ... ") urllib.request.urlretrieve(url_base + file_name, file_path) print("Done") def download_mnist(): for v in key_file.values(): _download(v) def _load_label(file_name): file_path = dataset_dir + "/" + file_name print("Converting " + file_name + " to NumPy Array ...") with gzip.open(file_path, 'rb') as f: labels = np.frombuffer(f.read(), np.uint8, offset=8) print("Done") return labels def _load_img(file_name): file_path = dataset_dir + "/" + file_name print("Converting " + file_name + " to NumPy Array ...") with gzip.open(file_path, 'rb') as f: data = np.frombuffer(f.read(), np.uint8, offset=16) data = data.reshape(-1, img_size) print("Done") return data def _convert_numpy(): dataset = {} dataset['train_img'] = _load_img(key_file['train_img']) dataset['train_label'] = _load_label(key_file['train_label']) dataset['test_img'] = _load_img(key_file['test_img']) dataset['test_label'] = _load_label(key_file['test_label']) return dataset def init_mnist(): download_mnist() dataset = _convert_numpy() print("Creating pickle file ...") with open(save_file, 'wb') as f: pickle.dump(dataset, f, -1) print("Done!") def _change_one_hot_label(X): T = np.zeros((X.size, 10)) for idx, row in enumerate(T): row[X[idx]] = 1 return T def load_mnist(normalize=True, flatten=True, one_hot_label=False): """读入MNIST数据集 Parameters ---------- normalize : 将图像的像素值正规化为0.0~1.0 one_hot_label : one_hot_label为True的情况下,标签作为one-hot数组返回 one-hot数组是指[0,0,1,0,0,0,0,0,0,0]这样的数组 flatten : 是否将图像展开为一维数组 Returns ------- (训练图像, 训练标签), (测试图像, 测试标签) """ if not os.path.exists(save_file): init_mnist() with open(save_file, 'rb') as f: dataset = pickle.load(f) if normalize: for key in ('train_img', 'test_img'): dataset[key] = dataset[key].astype(np.float32) dataset[key] /= 255.0 if one_hot_label: dataset['train_label'] = _change_one_hot_label(dataset['train_label']) dataset['test_label'] = _change_one_hot_label(dataset['test_label']) if not flatten: for key in ('train_img', 'test_img'): dataset[key] = dataset[key].reshape(-1, 1, 28, 28) return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label']) if name == 'main': init_mnist()模仿这段代码将获取同样形式

# Look through unique values in each categorical column categorical_cols = train_df.select_dtypes(include="object").columns.tolist() for col in categorical_cols: print(f"{col}", f"Number of unique entries: {len(train_df[col].unique().tolist())},") print(train_df[col].unique().tolist()) def plot_bar_chart(df, columns, grid_rows, grid_cols, x_label='', y_label='', title='', whole_numbers_only=False, count_labels=True, as_percentage=True): num_plots = len(columns) grid_size = grid_rows * grid_cols num_rows = math.ceil(num_plots / grid_cols) if num_plots == 1: fig, axes = plt.subplots(1, 1, figsize=(12, 8)) axes = [axes] # Wrap the single axes in a list for consistent handling else: fig, axes = plt.subplots(num_rows, grid_cols, figsize=(12, 8)) axes = axes.ravel() # Flatten the axes array to iterate over it for i, column in enumerate(columns): df_column = df[column] if whole_numbers_only: df_column = df_column[df_column % 1 == 0] ax = axes[i] y = [num for (s, num) in df_column.value_counts().items()] x = [s for (s, num) in df_column.value_counts().items()] ax.bar(x, y, color='blue', alpha=0.5) try: ax.set_xticks(range(x[-1], x[0] + 1)) except: pass ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_title(title + ' - ' + column) if count_labels: df_col = df_column.value_counts(normalize=True).mul(100).round(1).astype(str) + '%' for idx, (year, value) in enumerate(df_column.value_counts().items()): if as_percentage == False: ax.annotate(f'{value}\n', xy=(year, value), ha='center', va='center') else: ax.annotate(f'{df_col[year]}\n', xy=(year, value), ha='center', va='center', size=8) if num_plots < grid_size: for j in range(num_plots, grid_size): fig.delaxes(axes[j]) # Remove empty subplots if present plt.tight_layout() plt.show()

LDAM损失函数pytorch代码如下:class LDAMLoss(nn.Module): def init(self, cls_num_list, max_m=0.5, weight=None, s=30): super(LDAMLoss, self).init() m_list = 1.0 / np.sqrt(np.sqrt(cls_num_list)) m_list = m_list * (max_m / np.max(m_list)) m_list = torch.cuda.FloatTensor(m_list) self.m_list = m_list assert s > 0 self.s = s if weight is not None: weight = torch.FloatTensor(weight).cuda() self.weight = weight self.cls_num_list = cls_num_list def forward(self, x, target): index = torch.zeros_like(x, dtype=torch.uint8) index_float = index.type(torch.cuda.FloatTensor) batch_m = torch.matmul(self.m_list[None, :], index_float.transpose(1,0)) # 0,1 batch_m = batch_m.view((16, 1)) # size=(batch_size, 1) (-1,1) x_m = x - batch_m output = torch.where(index, x_m, x) if self.weight is not None: output = output * self.weight[None, :] target = torch.flatten(target) # 将 target 转换成 1D Tensor logit = output * self.s return F.cross_entropy(logit, target, weight=self.weight) 模型部分参数如下:# 设置全局参数 model_lr = 1e-5 BATCH_SIZE = 16 EPOCHS = 50 DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') use_amp = True use_dp = True classes = 7 resume = None CLIP_GRAD = 5.0 Best_ACC = 0 #记录最高得分 use_ema=True model_ema_decay=0.9998 start_epoch=1 seed=1 seed_everything(seed) # 数据增强 mixup mixup_fn = Mixup( mixup_alpha=0.8, cutmix_alpha=1.0, cutmix_minmax=None, prob=0.1, switch_prob=0.5, mode='batch', label_smoothing=0.1, num_classes=classes) 帮我用pytorch实现模型在模型训练中使用LDAM损失函数

import torch, os, cv2 from model.model import parsingNet from utils.common import merge_config from utils.dist_utils import dist_print import torch import scipy.special, tqdm import numpy as np import torchvision.transforms as transforms from data.dataset import LaneTestDataset from data.constant import culane_row_anchor, tusimple_row_anchor if __name__ == "__main__": torch.backends.cudnn.benchmark = True args, cfg = merge_config() dist_print('start testing...') assert cfg.backbone in ['18','34','50','101','152','50next','101next','50wide','101wide'] if cfg.dataset == 'CULane': cls_num_per_lane = 18 elif cfg.dataset == 'Tusimple': cls_num_per_lane = 56 else: raise NotImplementedError net = parsingNet(pretrained = False, backbone=cfg.backbone,cls_dim = (cfg.griding_num+1,cls_num_per_lane,4), use_aux=False).cuda() # we dont need auxiliary segmentation in testing state_dict = torch.load(cfg.test_model, map_location='cpu')['model'] compatible_state_dict = {} for k, v in state_dict.items(): if 'module.' in k: compatible_state_dict[k[7:]] = v else: compatible_state_dict[k] = v net.load_state_dict(compatible_state_dict, strict=False) net.eval() img_transforms = transforms.Compose([ transforms.Resize((288, 800)), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) if cfg.dataset == 'CULane': splits = ['test0_normal.txt', 'test1_crowd.txt', 'test2_hlight.txt', 'test3_shadow.txt', 'test4_noline.txt', 'test5_arrow.txt', 'test6_curve.txt', 'test7_cross.txt', 'test8_night.txt'] datasets = [LaneTestDataset(cfg.data_root,os.path.join(cfg.data_root, 'list/test_split/'+split),img_transform = img_transforms) for split in splits] img_w, img_h = 1640, 590 row_anchor = culane_row_anchor elif cfg.dataset == 'Tusimple': splits = ['test.txt'] datasets = [LaneTestDataset(cfg.data_root,os.path.join(cfg.data_root, split),img_transform = img_transforms) for split in splits] img_w, img_h = 1280, 720 row_anchor = tusimple_row_anchor else: raise NotImplementedError for split, dataset in zip(splits, datasets): loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle = False, num_workers=1) fourcc = cv2.VideoWriter_fourcc(*'MJPG') print(split[:-3]+'avi') vout = cv2.VideoWriter(split[:-3]+'avi', fourcc , 30.0, (img_w, img_h)) for i, data in enumerate(tqdm.tqdm(loader)): imgs, names = data imgs = imgs.cuda() with torch.no_grad(): out = net(imgs) col_sample = np.linspace(0, 800 - 1, cfg.griding_num) col_sample_w = col_sample[1] - col_sample[0] out_j = out[0].data.cpu().numpy() out_j = out_j[:, ::-1, :] prob = scipy.special.softmax(out_j[:-1, :, :], axis=0) idx = np.arange(cfg.griding_num) + 1 idx = idx.reshape(-1, 1, 1) loc = np.sum(prob * idx, axis=0) out_j = np.argmax(out_j, axis=0) loc[out_j == cfg.griding_num] = 0 out_j = loc # import pdb; pdb.set_trace() vis = cv2.imread(os.path.join(cfg.data_root,names[0])) for i in range(out_j.shape[1]): if np.sum(out_j[:, i] != 0) > 2: for k in range(out_j.shape[0]): if out_j[k, i] > 0: ppp = (int(out_j[k, i] * col_sample_w * img_w / 800) - 1, int(img_h * (row_anchor[cls_num_per_lane-1-k]/288)) - 1 ) cv2.circle(vis,ppp,5,(0,255,0),-1) vout.write(vis) vout.release()

给下面这段代码每行注释import os import json import torch from PIL import Image from torchvision import transforms from model import resnet34 def main(): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") data_transform = transforms.Compose( [transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # load image # 指向需要遍历预测的图像文件夹 imgs_root = "../dataset/val" assert os.path.exists(imgs_root), f"file: '{imgs_root}' dose not exist." # 读取指定文件夹下所有jpg图像路径 img_path_list = [os.path.join(imgs_root, i) for i in os.listdir(imgs_root) if i.endswith(".jpg")] # read class_indict json_path = './class_indices.json' assert os.path.exists(json_path), f"file: '{json_path}' dose not exist." json_file = open(json_path, "r") class_indict = json.load(json_file) # create model model = resnet34(num_classes=16).to(device) # load model weights weights_path = "./newresNet34.pth" assert os.path.exists(weights_path), f"file: '{weights_path}' dose not exist." model.load_state_dict(torch.load(weights_path, map_location=device)) # prediction model.eval() batch_size = 8 # 每次预测时将多少张图片打包成一个batch with torch.no_grad(): for ids in range(0, len(img_path_list) // batch_size): img_list = [] for img_path in img_path_list[ids * batch_size: (ids + 1) * batch_size]: assert os.path.exists(img_path), f"file: '{img_path}' dose not exist." img = Image.open(img_path) img = data_transform(img) img_list.append(img) # batch img # 将img_list列表中的所有图像打包成一个batch batch_img = torch.stack(img_list, dim=0) # predict class output = model(batch_img.to(device)).cpu() predict = torch.softmax(output, dim=1) probs, classes = torch.max(predict, dim=1) for idx, (pro, cla) in enumerate(zip(probs, classes)): print("image: {} class: {} prob: {:.3}".format(img_path_list[ids * batch_size + idx], class_indict[str(cla.numpy())], pro.numpy())) if __name__ == '__main__': main()

最新推荐

recommend-type

pytorch学习教程之自定义数据集

transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) train_dataset = MyDataset(root_dir='data/train', labels_file='train_labels.txt', transform=transform) val_dataset = ...
recommend-type

lxml-5.0.1-cp37-cp37m-win32.whl

lxml 是一个用于 Python 的库,它提供了高效的 XML 和 HTML 解析以及搜索功能。它是基于 libxml2 和 libxslt 这两个强大的 C 语言库构建的,因此相比纯 Python 实现的解析器(如 xml.etree.ElementTree),lxml 在速度和功能上都更为强大。 主要特性 快速的解析和序列化:由于底层是 C 实现的,lxml 在解析和序列化 XML/HTML 文档时非常快速。 XPath 和 CSS 选择器:支持 XPath 和 CSS 选择器,这使得在文档中查找特定元素变得简单而强大。 清理和转换 HTML:lxml 提供了强大的工具来清理和转换不规范的 HTML,比如自动修正标签和属性。 ETree API:提供了类似于 ElementTree 的 API,但更加完善和强大。 命名空间支持:相比 ElementTree,lxml 对 XML 命名空间提供了更好的支持。
recommend-type

Vue实现iOS原生Picker组件:详细解析与实现思路

"Vue.js实现iOS原生Picker效果及实现思路解析" 在iOS应用中,Picker组件通常用于让用户从一系列选项中进行选择,例如日期、时间或者特定的值。Vue.js作为一个流行的前端框架,虽然原生不包含与iOS Picker完全相同的组件,但开发者可以通过自定义组件来实现类似的效果。本篇文章将详细介绍如何在Vue.js项目中创建一个模仿iOS原生Picker功能的组件,并分享实现这一功能的思路。 首先,为了创建这个组件,我们需要一个基本的DOM结构。示例代码中给出了一个基础的模板,包括一个外层容器`<div class="pd-select-item">`,以及两个列表元素`<ul class="pd-select-list">`和`<ul class="pd-select-wheel">`,分别用于显示选定项和可滚动的选择项。 ```html <template> <div class="pd-select-item"> <div class="pd-select-line"></div> <ul class="pd-select-list"> <li class="pd-select-list-item">1</li> </ul> <ul class="pd-select-wheel"> <li class="pd-select-wheel-item">1</li> </ul> </div> </template> ``` 接下来,我们定义组件的属性(props)。`data`属性是必需的,它应该是一个数组,包含了所有可供用户选择的选项。`type`属性默认为'cycle',可能用于区分不同类型的Picker组件,例如循环滚动或非循环滚动。`value`属性用于设置初始选中的值。 ```javascript props: { data: { type: Array, required: true }, type: { type: String, default: 'cycle' }, value: {} } ``` 为了实现Picker的垂直居中效果,我们需要设置CSS样式。`.pd-select-line`, `.pd-select-list` 和 `.pd-select-wheel` 都被设置为绝对定位,通过`transform: translateY(-50%)`使其在垂直方向上居中。`.pd-select-list` 使用`overflow:hidden`来隐藏超出可视区域的部分。 为了达到iOS Picker的3D滚动效果,`.pd-select-wheel` 设置了`transform-style: preserve-3d`,确保子元素在3D空间中保持其位置。`.pd-select-wheel-item` 的每个列表项都设置了`position:absolute`,并使用`backface-visibility:hidden`来优化3D变换的性能。 ```css .pd-select-line, .pd-select-list, .pd-select-wheel { position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%); } .pd-select-list { overflow: hidden; } .pd-select-wheel { transform-style: preserve-3d; height: 30px; } .pd-select-wheel-item { white-space: nowrap; text-overflow: ellipsis; backface-visibility: hidden; position: absolute; top: 0px; width: 100%; overflow: hidden; } ``` 最后,为了使组件能够响应用户的滚动操作,我们需要监听触摸事件,更新选中项,并可能还需要处理滚动动画。这通常涉及到计算滚动位置,映射到数据数组,以及根据滚动方向调整可见项的位置。 总结来说,实现Vue.js中的iOS原生Picker效果,需要构建一个包含可滚动列表的自定义组件,通过CSS样式实现3D滚动效果,并通过JavaScript处理触摸事件来模拟Picker的行为。通过这种方式,开发者可以在Vue.js项目中创建出与iOS原生界面风格一致的用户交互体验。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【广度优先搜索】:Python面试中的系统化思维展现

![【广度优先搜索】:Python面试中的系统化思维展现](https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200611200432/Top-10-System-Design-Interview-Questions-and-Answers.png) # 1. 广度优先搜索(BFS)算法概述 广度优先搜索(Breadth-First Search, BFS)算法是图论中的一种基本算法,广泛应用于计算机科学和工程领域。它是对树或图进行遍历的一种方法,按照距离起点的远近逐层进行搜索,直到找到目标节点或遍历完所有可到达的节点。这种算法
recommend-type

nginx ubuntu离线安装

Nginx是一款开源的高性能Web服务器和反向代理服务器,常用于Linux系统,如Ubuntu。离线安装通常指在没有网络连接的情况下本地获取并配置软件包。以下是Nginx在Ubuntu上离线安装的基本步骤: 1. **下载Nginx包**: - 首先,你需要从Nginx官方网站下载适用于Ubuntu的二进制包。访问 https://nginx.org/en/download.html ,选择对应版本的`nginx`文件,比如`nginxxx.x.tar.gz`,将其保存到你的离线环境中。 2. **解压并移动文件**: 使用`tar`命令解压缩下载的文件: ```
recommend-type

Arduino蓝牙小车:参数调试与功能控制

本资源是一份基于Arduino Mega2560主控的蓝牙遥控小车程序代码,适用于Android设备通过蓝牙进行操控。该程序允许车辆实现运动、显示和测温等多种功能,具有较高的灵活性和实用性。 1. **蓝牙通信与模块操作** 在程序开始时,开发者提醒用户在上传代码前需将蓝牙模块的RX接口暂时拔掉,上传成功后再恢复连接。这可能是因为在调试过程中,需要确保串口通信的纯净性。程序通过Serial.begin()函数设置串口波特率为9600,这是常见的蓝牙通信速率,适合于手机等设备连接。 2. **电机控制参数调整** 代码中提到的"偏转角度需要根据场地不同进行调参数",表明程序设计为支持自定义参数,通过宏变量的形式,用户可以根据实际需求对小车的转向灵敏度进行个性化设置。例如,`#define left_forward_PIN4` 和 `#define right_forward_PIN2` 定义了左右轮的前进控制引脚,这些引脚的输出值范围是1-255,允许通过编程精确控制轮速。 3. **行驶方向控制** 小车的行驶方向通过改变特定引脚的高低电平来实现。例如,`void left_forward_PIN4` 和 `void left_back_PIN5` 分别控制左轮前进和后退,用户可以通过赋予高或低电平来指示小车的行驶方向。同时,右轮的控制方式类似。 4. **多种移动模式** 除了基本的前进和后退,程序还提供了原地左转、原地右转、右前、左前、左后和右后的控制函数,如`void turnLeftOrigin()` 等,增强了小车的机动性和操作多样性。 5. **主函数和循环结构** 主函数`void setup()`用于初始化硬件,包括串口通信和引脚配置。而`void loop()`则是一个无限循环,通过`void reve()`函数不断接收并处理蓝牙发送的指令,保持小车持续响应用户的控制命令。 6. **数据接收与解析** `void reve()`函数通过`Serial.parseInt()`读取蓝牙发送的数字值(7在示例中被提及),然后根据接收到的指令执行相应的移动命令,体现了程序的核心逻辑部分。 总结来说,这份蓝牙小车程序代码为开发人员提供了一个基础平台,通过调整参数和编写特定的控制函数,能够实现不同场景下的小车控制,具有较强的通用性和可扩展性。对于学习和实践Arduino与蓝牙通信的开发者来说,这是一个很好的学习和实践案例。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

【深度优先搜索】:Python算法面试的黄金钥匙

# 1. 深度优先搜索(DFS)概述 ## 1.1 深度优先搜索简介 深度优先搜索(DFS)是一种用于遍历或搜索树或图的算法。这种算法沿着树的深度遍历树的节点,尽可能深地搜索树的分支。当节点v的所有出边都被探寻过之后,搜索将回溯到发现节点v的那条边的起始节点。这种机制允许DFS解决多种类型的问题,例如寻找两个节点之间的路径、检测图中环的存在以及在计算机网络中进行拓扑排序等。 ## 1.2 深度优先搜索的特性 DFS最显著的特点是它的非形式化和直觉性的操作方式,它不需要额外的数据结构如优先队列来支持操作。相比于广度优先搜索,DFS在解决一些需要回溯和搜索深度较大分支的问题时更为高效。由于DF
recommend-type

vue3 fetch请求接口

在Vue 3中,fetch API是一种现代的JavaScript内置API,用于从服务器获取资源或发送数据。与axios类似,fetch也被广泛用于构建异步Web应用。以下是使用fetch进行请求的基本步骤: 1. 导入fetch:在Vue组件中,首先需要导入fetch,它是window对象的一部分,不需要额外安装依赖。 ```javascript import fetch from 'isomorphic-unfetch'; ``` 注意这里使用`isomorphic-unfetch`是为了提供跨环境支持(例如Node.js环境下的服务器端渲染)。 2. 发起请求:创建一个新的Pro