torch中怎么将array(['结构紧凑', '承载能力强', '加工机器人', '0.1'], dtype='<U20')这样的numpy数据embedding

时间: 2023-08-06 16:26:26 浏览: 45
在PyTorch中,可以使用`torch.nn.Embedding`模块来进行embedding操作。但是,`torch.nn.Embedding`模块需要输入的是整数类型的Tensor,而不是字符串或浮点数类型的Tensor。所以,在将字符串或浮点数类型的Tensor进行embedding之前,需要先将其转换为整数类型的Tensor。 以下是一个示例代码,用于将字符串类型的Tensor转换为整数类型的Tensor,并进行embedding操作: ```python import numpy as np import torch # 定义一个字符串类型的Tensor str_tensor = torch.tensor(['结构紧凑', '承载能力强', '加工机器人', '0.1']) # 将字符串类型的Tensor转换为整数类型的Tensor word_to_ix = {} for word in str_tensor: if word not in word_to_ix: word_to_ix[word] = len(word_to_ix) ix_to_word = {ix: word for word, ix in word_to_ix.items()} int_tensor = torch.tensor([word_to_ix[word] for word in str_tensor], dtype=torch.long) # 定义embedding层 embedding_layer = torch.nn.Embedding(len(word_to_ix), 10) # 进行embedding操作 embedded_tensor = embedding_layer(int_tensor) print(embedded_tensor) ``` 在上面的示例代码中,我们首先将字符串类型的Tensor转换为整数类型的Tensor,其中`word_to_ix`字典用于将每个字符串映射到一个整数,`ix_to_word`字典用于将整数映射回原来的字符串。然后,我们定义了一个embedding层,其中`len(word_to_ix)`表示embedding层的输入大小,`10`表示embedding层的输出大小。最后,我们使用`embedding_layer`对整数类型的Tensor进行embedding操作,得到嵌入后的Tensor。 需要注意的是,上面示例代码中,我们使用了固定的embedding层输入和输出大小。在实际应用中,这些大小需要根据数据集的特点进行调整。

相关推荐

coding=UTF-8 from flask import Flask, render_template, request, send_from_directory from werkzeug.utils import secure_filename from iconflow.model.colorizer import ReferenceBasedColorizer from skimage.feature import canny as get_canny_feature from torchvision import transforms from PIL import Image import os import datetime import torchvision import cv2 import numpy as np import torch import einops transform_Normalize = torchvision.transforms.Compose([ transforms.Normalize(0.5, 1.0)]) ALLOWED_EXTENSIONS = set([‘png’, ‘jpg’, ‘jpeg’]) app = Flask(name) train_model = ReferenceBasedColorizer() basepath = os.path.join( os.path.dirname(file), ‘images’) # 当前文件所在路径 def allowed_file(filename): return ‘.’ in filename and filename.rsplit(‘.’, 1)[1] in ALLOWED_EXTENSIONS def load_model(log_path=‘/mnt/4T/lzq/IconFlowPaper/checkpoints/normal_model.pt’): global train_model state = torch.load(log_path) train_model.load_state_dict(state[‘net’]) @app.route(“/”, methods=[“GET”, “POST”]) def hello(): if request.method == ‘GET’: return render_template(‘upload.html’) @app.route(‘/upload’, methods=[“GET”, “POST”]) def upload_lnk(): if request.method == ‘GET’: return render_template(‘upload.html’) if request.method == ‘POST’: try: file = request.files['uploadimg'] except Exception: return None if file and allowed_file(file.filename): format = "%Y-%m-%dT%H:%M:%S" now = datetime.datetime.utcnow().strftime(format) filename = now + '_' + file.filename filename = secure_filename(filename) basepath = os.path.join( os.path.dirname(file), ‘images’) # 当前文件所在路径 # upload_path = os.path.join(basepath,secure_filename(f.filename)) file.save(os.path.join(basepath, filename)) else: filename = None return filename @app.route(‘/download/string:filename’, methods=[‘GET’]) def download(filename): if request.method == “GET”: if os.path.isfile(os.path.join(basepath, filename)): return send_from_directory(basepath, filename, as_attachment=True) pass def get_contour(img): x = np.array(img) canny = 0 for layer in np.rollaxis(x, -1): canny |= get_canny_feature(layer, 0) canny = canny.astype(np.uint8) * 255 kernel = np.array([ [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], ], dtype=np.uint8) canny = cv2.dilate(canny, kernel) # canny = Image.fromarray(canny) return canny @app.route(‘/embedding//’, methods=[“GET”, “POST”]) def icontran(img, reference): global train_model if request.method == ‘POST’: imgPath = os.path.join(basepath, img) referencePath = os.path.join(basepath, reference) img = cv2.imread(imgPath) if img is None or img.size <= 0: return None contour = get_contour(img).astype(np.float32).copy() contour = 255 - contour reference = cv2.imread(referencePath).astype(np.float32) reference = cv2.cvtColor(reference, cv2.COLOR_BGR2RGB) reference = transform_Normalize(torch.from_numpy(reference).permute(2, 0, 1).unsqueeze(0).float()/ 255.0) contour = transform_Normalize(torch.from_numpy(contour).unsqueeze(0).unsqueeze(0).float()/ 255.0) train_model.eval() transfer = train_model(contour, reference) transfer = transfer.squeeze(0) transfer = (transfer + 0.5).clamp(0, 1).mul_(255).permute(1, 2, 0).type(torch.uint8).numpy() transfer = transfer.numpy() cv2.imwrite(imgPath, transfer) return basepath # success if name == “main”: load_model() app.run(host=‘10.21.16.144’, port=9999, debug=True) 用puthon写一个调用这个服务器的gui

最新推荐

recommend-type

Pytorch中torch.nn的损失函数

一、torch.nn.BCELoss(weight=None, size_average=True) 二、nn.BCEWithLogitsLoss(weight=None, size_average=True) 三、torch.nn.MultiLabelSoftMarginLoss(weight=None, size_average=True) 四、总结 前言 最近...
recommend-type

Pytorch中torch.gather函数

在学习 CS231n中的NetworkVisualization-PyTorch任务,讲解了使用torch.gather函数,gather函数是用来根据你输入的位置索引 index,来对张量位置的数据进行合并,然后再输出。 其中 gather有两种使用方式,一种为 ...
recommend-type

在C++中加载TorchScript模型的方法

主要介绍了在C++中加载TorchScript模型的方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
recommend-type

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

自定义数据集 在训练深度学习模型之前,样本集的制作非常重要。在pytorch中,提供了一些接口和类,方便我们定义自己的数据集合,下面完整的试验自定义样本集的整个流程。 开发环境 Ubuntu 18.04 pytorch 1.0 ...
recommend-type

pytorch 实现数据增强分类 albumentations的使用

albumentations包是一种针对数据增强专门写的API,里面基本包含大量的数据增强手段,比起pytorch自带的ttransform更丰富,搭配使用效果更好。 代码和效果 import albumentations import cv2 from PIL import Image, ...
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

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

优化MATLAB分段函数绘制:提升效率,绘制更快速

![优化MATLAB分段函数绘制:提升效率,绘制更快速](https://ucc.alicdn.com/pic/developer-ecology/666d2a4198c6409c9694db36397539c1.png?x-oss-process=image/resize,s_500,m_lfit) # 1. MATLAB分段函数绘制概述** 分段函数绘制是一种常用的技术,用于可视化不同区间内具有不同数学表达式的函数。在MATLAB中,分段函数可以通过使用if-else语句或switch-case语句来实现。 **绘制过程** MATLAB分段函数绘制的过程通常包括以下步骤: 1.
recommend-type

SDN如何实现简易防火墙

SDN可以通过控制器来实现简易防火墙。具体步骤如下: 1. 定义防火墙规则:在控制器上定义防火墙规则,例如禁止某些IP地址或端口访问,或者只允许来自特定IP地址或端口的流量通过。 2. 获取流量信息:SDN交换机会将流量信息发送给控制器。控制器可以根据防火墙规则对流量进行过滤。 3. 过滤流量:控制器根据防火墙规则对流量进行过滤,满足规则的流量可以通过,不满足规则的流量则被阻止。 4. 配置交换机:控制器根据防火墙规则配置交换机,只允许通过满足规则的流量,不满足规则的流量则被阻止。 需要注意的是,这种简易防火墙并不能完全保护网络安全,只能起到一定的防护作用,对于更严格的安全要求,需要
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。