给我一个推理和动作控制的单线程代码 import os import torch import torch.nn as nn from torchvision import…
- User
给我一个推理和动作控制的单线程代码 import os import torch import torch.nn as nn from torchvision import transforms from torchvision.models import resnet50, ResNet50_Weights from PIL import Image import queue import threading import mss from pynput.keyboard import Key, Controller as KeyboardController import pydirectinput
---- 模型定义 ----
class MultiTaskResNet(nn.Module): def init(self, base_model): super(MultiTaskResNet, self).init() self.shared_features = nn.Sequential(*list(base_model.children())[:-1]) # 特征提取器 self.action_head = nn.Sequential( nn.Linear(base_model.fc.in_features, 128), nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, 8), # 动作头(预测8类动作) ) self.offset_head = nn.Sequential( nn.Linear(base_model.fc.in_features, 128), nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, 2) # 偏移头(预测 dx 和 dy) )
def forward(self, x): features = self.shared_features(x).flatten(1) # 特征提取后展平 actions = self.action_head(features) # 动作预测 offsets = self.offset_head(features) # 偏移预测 return actions, offsets---- 加载模型 ----
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
加载 ResNet50 基础模型
base_model = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2) model = MultiTaskResNet(base_model).to(device).eval()
加载训练好的权重(确保路径正确)
model.load_state_dict(torch.load("model_final.pth", map_location=device)) # 替换为你的模型路径 model = model.float()
---- 图像预处理 ----
transform = transforms.Compose([ transforms.Resize((224, 224)), # 调整图像大小 transforms.ToTensor(), # 转换为张量 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # 标准化 ])
---- 分段反归一化工具函数 ----
def denormalize(value, core_min, core_max, global_min, global_max): if value < 0.2: return value * (core_min - global_min) / 0.2 + global_min elif value > 0.8: return (value - 0.8) * (global_max - core_max) / 0.2 + core_max else: return (value - 0.2) * (core_max - core_min) / 0.6 + core_min
鼠标 dx/dy 偏移值范围
core_dx_min, core_dx_max = -8, 8 core_dy_min, core_dy_max = -3, 3 dx_min, dx_max = -312, 230 dy_min, dy_max = -64, 140
---- 推理函数 ----
def predict(image): """ 推理函数,用于对输入图像进行动作和鼠标偏移预测。 输入: - image: 一个 PIL 图像 输出: - 动作数组和鼠标坐标偏移 [W, S, A, D, R, Space, Shift, MouseLeft, dx, dy] """ # 图像预处理 image_tensor = transform(image).unsqueeze(0).to(device)
# 禁用梯度计算,提高推理效率 with torch.no_grad(): # 模型推理 actions_logits, offsets_raw = model(image_tensor) # 对动作信号应用 Sigmoid 激活,二值化输出 actions = (torch.sigmoid(actions_logits) > 0.5).squeeze(0).cpu().numpy().astype(int) # 对鼠标 dx 和 dy 应用反归一化 dx = denormalize(offsets_raw[0, 0].item(), core_dx_min, core_dx_max, dx_min, dx_max) dy = denormalize(offsets_raw[0, 1].item(), core_dy_min, core_dy_max, dy_min, dy_max) # 打印调试信息 print(f"Predicted Actions: {actions}, dx: {dx:.2f}, dy: {dy:.2f}") return list(actions) + [dx, dy] - Assistant
- User
更改我的代码,去除我代码的多线程
- Assistant
- User
控制按键,我希望程序能同时执行W,D类似的双按键和普通的W类似的单按键
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.