由头
小弟初学AI,毕设是做多模态情感分析,刚好搜到佬的项目,于是怀着膜拜之心下载、阅读、训练。我现在想的是做一个前端,用户输入文本和图像,然后调用训练好的模型对其进行情感分类。
问题
但是我看不太懂你的数据处理方式,具体来说我无法处理用户输入的文本-图像数据,我发现你的数据貌似是要使用json格式进行提取(我不懂哈),然后我就怎么着也不能完美的处理外界数据。
代码
- 1.我在项目目录中新建了web目录,在web目录下新建run_model.py文件(其余web目录下的文件暂时忽略/(ㄒoㄒ)/~~),如下:
- 3.这是run_model.py文件内容:
``
import sys
import os
指定自定义streamlit模块的绝对路径
custom_streamlit_path = 'E:/aGraduation_Program_File/Multimodal-Sentiment-Analysis-main/'
如果这个路径还不在sys.path中,就添加进去
if custom_streamlit_path not in sys.path:
sys.path.insert(0, custom_streamlit_path)
现在,尝试导入streamlit
import streamlit as st
from PIL import Image
import torch
from torchvision import transforms
#from transformers import AutoTokenizer
import io
from Models.OTEModel import Model # 根据实际使用的模型进行调整
from utils.DataProcess import LabelVocab # LabelVocab在Dataprocess.py中定义
from utils.APIs.APIDecode import api_decode # 解码模型输出的函数
from Config import config # 导入配置信息
配置信息
config = config()
加载模型
def load_model(model_path):
model = Model(config) # 假设模型初始化需要配置信息
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
model.eval()
return model
model_path = "E:/aGraduation_Program_File/Multimodal-Sentiment-Analysis-main/output/OTE/pytorch_model.bin"
model = load_model(model_path)
初始化tokenizer和LabelVocab
#tokenizer = AutoTokenizer.from_pretrained(config.bert_name)
label_vocab = LabelVocab()
图像预处理函数
def process_image(image):
def get_resize(image_size):
for i in range(20):
if 2 ** i >= image_size:
return 2 ** i
return image_size
img_transform = transforms.Compose([
transforms.Resize(get_resize(config.image_size)),
transforms.CenterCrop(config.image_size),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
image = Image.open(io.BytesIO(image.read()))
return img_transform(image).unsqueeze(0)
文本预处理函数
'''def process_text(text):
text = text.replace('#', '')
tokens = tokenizer('[CLS]' + text + '[SEP]', return_tensors="pt", padding=True, truncation=True, max_length=512)
return tokens['input_ids'], tokens['attention_mask']
'''
from transformers import RobertaTokenizer
从本地路径加载 'roberta-base' 分词器
tokenizer = RobertaTokenizer.from_pretrained('C:/Users/Lenovo/.cache/huggingface/hub/models--roberta-base')
def preprocess_text(text, max_length=512):
"""
对给定文本进行预处理,生成input_ids和attention_mask。
参数:
- text (str): 输入文本。
- max_length (int): 文本的最大长度。
返回:
- input_ids (torch.Tensor): 文本的input ids。
- attention_mask (torch.Tensor): 文本的attention mask。
"""
# 使用encode_plus方法对文本进行编码
encoded_dict = tokenizer.encode_plus(
text, # 输入文本
add_special_tokens=True, # 添加特殊标记
max_length=max_length, # 设定最大文本长度
padding='max_length', # 填充至max_length长度
truncation=True, # 超过max_length会被截断
return_attention_mask=True, # 返回attention mask
return_tensors='pt', # 返回PyTorch张量
)
input_ids = encoded_dict['input_ids']
attention_mask = encoded_dict['attention_mask']
print("run_model")
print(input_ids.shape, attention_mask.shape)
return input_ids, attention_mask
'''
def preprocess_text(text, max_length=512):
"""
对给定文本进行预处理,生成input_ids和attention_mask。
参数:
- text (str): 输入文本。
- max_length (int): 文本的最大长度。
返回:
- input_ids (torch.Tensor): 文本的input ids。
- attention_mask (torch.Tensor): 文本的attention mask。
"""
# 使用encode_plus方法对文本进行编码
encoded_dict = tokenizer.encode_plus(
text, # 输入文本
add_special_tokens=True, # 添加'[CLS]'和'[SEP]'
max_length=max_length, # 设定最大文本长度
pad_to_max_length=True, # 填充至max_length长度
return_attention_mask=True, # 返回attention mask
return_tensors='pt', # 返回PyTorch张量
)
input_ids = encoded_dict['input_ids']
attention_mask = encoded_dict['attention_mask']
return input_ids, attention_mask
'''
应用标题
st.title("多模态情感分析")
文件上传器
uploaded_image = st.file_uploader("上传图片", type=["jpg", "jpeg", "png"])
uploaded_text = st.text_area("输入文本", "")
if uploaded_image is not None and uploaded_text != "":
processed_image = process_image(uploaded_image)
input_ids, attention_mask = preprocess_text(uploaded_text)
# 假设你的模型接受已经处理的图像和文本作为输入,并返回情感分类结果
# 你需要根据你的模型具体实现调整下面的预测代码
with torch.no_grad():
prediction = model(processed_image, input_ids, attention_mask)
sentiment = api_decode(prediction, label_vocab) # 假设api_decode能够根据预测结果返回情感标签
st.write(f"预测情感: {sentiment}")
``
run_model.md