Deeplearning/test2.py

56 lines
1.6 KiB
Python
Raw Normal View History

2024-10-07 09:54:32 +08:00
import pandas as pd
import torch
from torch.utils.data import DataLoader, TensorDataset
# 读取Excel文件
df = pd.read_excel('loss-metal-compress.xlsx')
# 假设你的模型需要的数据是前300行
data = df.iloc[300:600, 1].values
# 将数据转换为Tensor
data_tensor = torch.tensor(data, dtype=torch.float32).unsqueeze(0) # 增加一个批次维度
# 需要填充的0的数量
padding_size = 371 - data_tensor.size(1)
# 如果需要填充的0的数量大于0则进行填充
if padding_size > 0:
# 创建一个形状为[1, padding_size]的0张量
padding_tensor = torch.zeros(1, padding_size, dtype=torch.float32)
# 将原始数据和0张量拼接起来
data_tensor_padded = torch.cat((data_tensor, padding_tensor), dim=1)
else:
data_tensor_padded = data_tensor
# 包装成TensorDataset和DataLoader
dataset = TensorDataset(data_tensor_padded)
dataloader = DataLoader(dataset, batch_size=1, shuffle=False)
# 确定设备
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# device = 'cpu'
print(f"Using device: {device}")
# 加载你的模型
model = torch.load('Sound.pth', map_location=device) # 确保模型加载到正确的设备
model.to(device) # 再次确保模型在正确的设备上
model.eval() # 设置为评估模式
# 进行预测
predictions = []
with torch.no_grad():
for batch in dataloader:
inputs = batch[0].to(device) # 将输入数据移动到相同的设备
outputs = model(inputs)
_, predicted = torch.max(outputs, 1)
predictions.extend(predicted.cpu().numpy()) # 将预测结果移动回CPU并转换为numpy数组
# 打印预测结果
print(predictions)