当前位置: 首页 > news >正文

做网站的盈利点用什么做网站开发

做网站的盈利点,用什么做网站开发,仙桃网站建设,wordpress wp rocket基于WIN10的64位系统演示 一、写在前面 本期开始#xff0c;我们学习深度学习图像目标检测系列。 深度学习图像目标检测是计算机视觉领域的一个重要子领域#xff0c;它的核心目标是利用深度学习模型来识别并定位图像中的特定目标。这些目标可以是物体、人、动物或其他可识…基于WIN10的64位系统演示 一、写在前面 本期开始我们学习深度学习图像目标检测系列。 深度学习图像目标检测是计算机视觉领域的一个重要子领域它的核心目标是利用深度学习模型来识别并定位图像中的特定目标。这些目标可以是物体、人、动物或其他可识别的实体。与传统的图像分类任务不同目标检测不仅要确定图像中存在哪些类别的目标还要确定它们的确切位置和尺寸。这通常是通过在图像上绘制一个或多个边界框来实现的这些边界框精确地标出了目标的位置和范围。 二、Faster R-CNN简介 Faster R-CNN 是一种流行的深度学习图像目标检测算法由 Shaoqing Ren, Kaiming He, Ross Girshick 和 Jian Sun 在 2015 年提出。它是 R-CNN 系列模型中的一个重要里程碑因为它提高了检测速度同时保持了高精度。以下是 Faster R-CNN 的主要特点和组件 1区域提议网络 (RPN) Faster R-CNN 的核心创新是引入了一个叫做区域提议网络 (RPN) 的组件。RPN 能够在卷积特征图上直接生成目标的边界框提议这大大减少了提议的计算时间。RPN 使用了一组固定大小和比例的锚框anchors对每一个锚框预测偏移量和目标存在的概率。 2共享卷积特征 与其前任 Fast R-CNN 不同Faster R-CNN 的 RPN 和最终的目标检测都共享相同的卷积特征。这意味着图像只需要进行一次前向传播从而大大提高了计算效率。 3ROI Pooling 一旦得到了区域提议Faster R-CNN 使用 ROI (Region of Interest) Pooling 技术来从每个提议中提取固定大小的特征。这确保无论提议的大小如何都可以输入到一个固定大小的全连接网络中进行分类和边界框回归。 4双任务损失 RPN 被训练为一个双任务问题分类目标 vs. 非目标和边界框回归。这种双任务损失结构确保了 RPN 在生成提议时既考虑了准确性也考虑了定位。 总之Faster R-CNN 通过引入区域提议网络和共享卷积特征大大提高了目标检测的速度和精度为后续的研究和应用打下了坚实的基础。 三、数据源 来源于公共数据文件设置如下 大概的任务就是用一个框框标记出MTB的位置。 四、Faster R-CNN实战 直接上代码 import os import random import torch import torchvision from torchvision.models.detection import fasterrcnn_resnet50_fpn from torchvision.transforms import functional as F from PIL import Image from torch.utils.data import DataLoader import xml.etree.ElementTree as ET from torchvision.models.detection.faster_rcnn import FastRCNNPredictor import matplotlib.pyplot as plt from torchvision import transforms import albumentations as A from albumentations.pytorch import ToTensorV2 import numpy as np# Function to parse XML annotations def parse_xml(xml_path):tree ET.parse(xml_path)root tree.getroot()boxes []for obj in root.findall(object):bndbox obj.find(bndbox)xmin int(bndbox.find(xmin).text)ymin int(bndbox.find(ymin).text)xmax int(bndbox.find(xmax).text)ymax int(bndbox.find(ymax).text)# Check if the bounding box is validif xmin xmax and ymin ymax:boxes.append((xmin, ymin, xmax, ymax))else:print(fWarning: Ignored invalid box in {xml_path} - ({xmin}, {ymin}, {xmax}, {ymax}))return boxes# Function to split data into training and validation sets def split_data(image_dir, split_ratio0.8):all_images [f for f in os.listdir(image_dir) if f.endswith(.jpg)]random.shuffle(all_images)split_idx int(len(all_images) * split_ratio)train_images all_images[:split_idx]val_images all_images[split_idx:]return train_images, val_images# Dataset class for the Tuberculosis dataset class TuberculosisDataset(torch.utils.data.Dataset):def __init__(self, image_dir, annotation_dir, image_list, transformNone):self.image_dir image_dirself.annotation_dir annotation_dirself.image_list image_listself.transform transformdef __len__(self):return len(self.image_list)def __getitem__(self, idx):image_path os.path.join(self.image_dir, self.image_list[idx])image Image.open(image_path).convert(RGB)xml_path os.path.join(self.annotation_dir, self.image_list[idx].replace(.jpg, .xml))boxes parse_xml(xml_path)# Check for empty bounding boxes and return Noneif len(boxes) 0:return Noneboxes torch.as_tensor(boxes, dtypetorch.float32)labels torch.ones((len(boxes),), dtypetorch.int64)iscrowd torch.zeros((len(boxes),), dtypetorch.int64)target {}target[boxes] boxestarget[labels] labelstarget[image_id] torch.tensor([idx])target[iscrowd] iscrowd# Apply transformationsif self.transform:image self.transform(image)return image, target# Define the transformations using torchvision data_transform torchvision.transforms.Compose([torchvision.transforms.ToTensor(), # Convert PIL image to tensortorchvision.transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]) # Normalize the images ])# Adjusting the DataLoader collate function to handle None values def collate_fn(batch):batch list(filter(lambda x: x is not None, batch))return tuple(zip(*batch))# Function to get the Mask R-CNN model def get_model(num_classes):model fasterrcnn_resnet50_fpn(pretrainedTrue)in_features model.roi_heads.box_predictor.cls_score.in_featuresmodel.roi_heads.box_predictor FastRCNNPredictor(in_features, num_classes)return model# Function to save the model def save_model(model, pathmmaskrcnn_mtb.pth, save_full_modelFalse):if save_full_model:torch.save(model, path)else:torch.save(model.state_dict(), path)print(fModel saved to {path})# Function to compute Intersection over Union def compute_iou(boxA, boxB):xA max(boxA[0], boxB[0])yA max(boxA[1], boxB[1])xB min(boxA[2], boxB[2])yB min(boxA[3], boxB[3])interArea max(0, xB - xA 1) * max(0, yB - yA 1)boxAArea (boxA[2] - boxA[0] 1) * (boxA[3] - boxA[1] 1)boxBArea (boxB[2] - boxB[0] 1) * (boxB[3] - boxB[1] 1)iou interArea / float(boxAArea boxBArea - interArea)return iou# Adjusting the DataLoader collate function to handle None values and entirely empty batches def collate_fn(batch):batch list(filter(lambda x: x is not None, batch))if len(batch) 0:# Return placeholder batch if entirely emptyreturn [torch.zeros(1, 3, 224, 224)], [{}]return tuple(zip(*batch))#Training function with modifications for collecting IoU and loss def train_model(model, train_loader, optimizer, device, num_epochs10):model.train()model.to(device)loss_values []iou_values []for epoch in range(num_epochs):epoch_loss 0.0total_ious 0num_boxes 0for images, targets in train_loader:# Skip batches with placeholder dataif len(targets) 1 and not targets[0]:continue# Skip batches with empty targetsif any(len(target[boxes]) 0 for target in targets):continueimages [image.to(device) for image in images]targets [{k: v.to(device) for k, v in t.items()} for t in targets]loss_dict model(images, targets)losses sum(loss for loss in loss_dict.values())optimizer.zero_grad()losses.backward()optimizer.step()epoch_loss losses.item()# Compute IoU for evaluationwith torch.no_grad():model.eval()predictions model(images)for i, prediction in enumerate(predictions):pred_boxes prediction[boxes].cpu().numpy()true_boxes targets[i][boxes].cpu().numpy()for pred_box in pred_boxes:for true_box in true_boxes:iou compute_iou(pred_box, true_box)total_ious iounum_boxes 1model.train()avg_loss epoch_loss / len(train_loader)avg_iou total_ious / num_boxesloss_values.append(avg_loss)iou_values.append(avg_iou)print(fEpoch {epoch1}/{num_epochs} Loss: {avg_loss} Avg IoU: {avg_iou})# Plotting loss and IoU valuesplt.figure(figsize(12, 5))plt.subplot(1, 2, 1)plt.plot(loss_values, labelTraining Loss)plt.title(Training Loss across Epochs)plt.xlabel(Epochs)plt.ylabel(Loss)plt.subplot(1, 2, 2)plt.plot(iou_values, labelIoU)plt.title(IoU across Epochs)plt.xlabel(Epochs)plt.ylabel(IoU)plt.show()# Save model after trainingsave_model(model)# Validation function def validate_model(model, val_loader, device):model.eval()model.to(device)with torch.no_grad():for images, targets in val_loader:images [image.to(device) for image in images]targets [{k: v.to(device) for k, v in t.items()} for t in targets]model(images)# Paths to your data image_dir tuberculosis-phonecamera annotation_dir tuberculosis-phonecamera# Split data train_images, val_images split_data(image_dir)# Create datasets and dataloaders train_dataset TuberculosisDataset(image_dir, annotation_dir, train_images, transformdata_transform) val_dataset TuberculosisDataset(image_dir, annotation_dir, val_images, transformdata_transform)# Updated DataLoader with new collate function train_loader DataLoader(train_dataset, batch_size4, shuffleTrue, collate_fncollate_fn) val_loader DataLoader(val_dataset, batch_size4, shuffleFalse, collate_fncollate_fn)# Model and optimizer model get_model(2) optimizer torch.optim.SGD(model.parameters(), lr0.005, momentum0.9, weight_decay0.0005)# Train and validate train_model(model, train_loader, optimizer, devicecuda, num_epochs100) validate_model(model, val_loader, devicecuda)#######################################Print Metrics###################################### def calculate_metrics(predictions, ground_truths, iou_threshold0.5):TP 0 # True PositivesFP 0 # False PositivesFN 0 # False Negativestotal_iou 0 # to calculate mean IoUfor pred, gt in zip(predictions, ground_truths):pred_boxes pred[boxes].cpu().numpy()gt_boxes gt[boxes].cpu().numpy()# Match predicted boxes to ground truth boxesfor pred_box in pred_boxes:max_iou 0matched Falsefor gt_box in gt_boxes:iou compute_iou(pred_box, gt_box)if iou max_iou:max_iou iouif iou iou_threshold:matched Truetotal_iou max_iouif matched:TP 1else:FP 1FN len(gt_boxes) - TPprecision TP / (TP FP) if (TP FP) ! 0 else 0recall TP / (TP FN) if (TP FN) ! 0 else 0f1_score (2 * precision * recall) / (precision recall) if (precision recall) ! 0 else 0mean_iou total_iou / (TP FP)return precision, recall, f1_score, mean_ioudef evaluate_model(model, dataloader, device):model.eval()model.to(device)all_predictions []all_ground_truths []with torch.no_grad():for images, targets in dataloader:images [image.to(device) for image in images]predictions model(images)all_predictions.extend(predictions)all_ground_truths.extend(targets)precision, recall, f1_score, mean_iou calculate_metrics(all_predictions, all_ground_truths)return precision, recall, f1_score, mean_ioutrain_precision, train_recall, train_f1, train_iou evaluate_model(model, train_loader, cuda) val_precision, val_recall, val_f1, val_iou evaluate_model(model, val_loader, cuda)print(Training Set Metrics:) print(fPrecision: {train_precision:.4f}, Recall: {train_recall:.4f}, F1 Score: {train_f1:.4f}, Mean IoU: {train_iou:.4f})print(\nValidation Set Metrics:) print(fPrecision: {val_precision:.4f}, Recall: {val_recall:.4f}, F1 Score: {val_f1:.4f}, Mean IoU: {val_iou:.4f})#sheet header | Metric | Training Set | Validation Set | divider ----------------------------------------train_metrics f| Precision | {train_precision:.4f} | {val_precision:.4f} | recall_metrics f| Recall | {train_recall:.4f} | {val_recall:.4f} | f1_metrics f| F1 Score | {train_f1:.4f} | {val_f1:.4f} | iou_metrics f| Mean IoU | {train_iou:.4f} | {val_iou:.4f} |print(header) print(divider) print(train_metrics) print(recall_metrics) print(f1_metrics) print(iou_metrics) print(divider)#######################################Train Set###################################### import numpy as np import matplotlib.pyplot as pltdef plot_predictions_on_image(model, dataset, device, title):# Select a random image from the datasetidx np.random.randint(50, len(dataset))image, target dataset[idx]img_tensor image.clone().detach().to(device).unsqueeze(0)# Use the model to make predictionsmodel.eval()with torch.no_grad():prediction model(img_tensor)# Inverse normalization for visualizationinv_normalize transforms.Normalize(mean[-0.485/0.229, -0.456/0.224, -0.406/0.225],std[1/0.229, 1/0.224, 1/0.225])image inv_normalize(image)image torch.clamp(image, 0, 1)image F.to_pil_image(image)# Plot the image with ground truth boxesplt.figure(figsize(10, 6))plt.title(title with Ground Truth Boxes)plt.imshow(image)ax plt.gca()# Draw the ground truth boxes in bluefor box in target[boxes]:rect plt.Rectangle((box[0], box[1]), box[2]-box[0], box[3]-box[1],fillFalse, colorblue, linewidth2)ax.add_patch(rect)plt.show()# Plot the image with predicted boxesplt.figure(figsize(10, 6))plt.title(title with Predicted Boxes)plt.imshow(image)ax plt.gca()# Draw the predicted boxes in redfor box in prediction[0][boxes].cpu():rect plt.Rectangle((box[0], box[1]), box[2]-box[0], box[3]-box[1],fillFalse, colorred, linewidth2)ax.add_patch(rect)plt.show()# Call the function for a random image from the train dataset plot_predictions_on_image(model, train_dataset, cuda, Selected from Training Set)#######################################Val Set####################################### Call the function for a random image from the validation dataset plot_predictions_on_image(model, val_dataset, cuda, Selected from Validation Set) 不解读了给出GPT的咒语参考 咒语我有一批数据存在“tuberculosis-phonecamera”文件夹中包括两部分 一部分是MTB的痰涂片抗酸染色图片为jpg格式命名为“tuberculosis-phone-0001.jpg”、“tuberculosis-phone-0002.jpg”等 一部分是MTB的痰涂片抗酸染色图片对应的注释文件主要内容是标注MTB的痰涂片抗酸染色图片中MTB的具体位置是若干个红色框为XML格式命名为“tuberculosis-phone-0001.xml”、“tuberculosis-phone-0002.xml”等我上传一个xml文件给你做例子 我需要基于上面的数据使用pytorch建立一个Mask R-CNN目标识别模型去识别MTB的痰涂片抗酸染色图片中的MTB并使用红色框标注出来。数据需要随机分为训练集80%和验证集20%。 看看结果 1loss曲线图 2性能指标 3训练的图片测试结果 4验证集的图片测试结果 五、写在后面 直接使用预训练模型而且模型并没有调参。但是训练集的准确率还是挺高的验证集就差点意思了。需要更高的性能还得认真研究如何调参。
http://www.tj-hxxt.cn/news/218252.html

相关文章:

  • 网站备案号含义那里有专做粮食的网站
  • 百度网站模板免费下载迅雷资源做下载网站
  • 房地产网站欣赏推广方式有哪些渠道
  • 天元建设集团有限公司法定代表人宁波专业seo团队
  • 国家电网交流建设分公司网站网站域名中文后缀
  • 做电影网站会违法吗湖南人文科技学院全国排名
  • 鲜花网站建设介绍wordpress常规设置
  • 后期网站建设及维护推广丽水 网站建设
  • 南城网站建设价格贵阳网站建设费用多少网帮你
  • 福州网站设计外包上海的咨询公司排名
  • 昌平上门做网站那高级网站开发培训
  • 网站到期如何续费项目计划书ppt
  • 做心理咨询可以在哪些网站发贴深圳房地产信息平台官网
  • 深圳建站网站公司小程序怎么做网站
  • 苏州高端网站设计企业低调赚大钱的灰色行业
  • 龙门石窟网站建设策划报告那家财经网站做的好
  • 网站建设费如何记账如何做返利网站
  • 长沙网站建设网网站开发费入什么费用
  • 一个域名可以做几个网站栾城哪家公司做网站
  • 个人公司网站建设答辩莱州网站建设包年
  • 订餐网站开发流程广告设计宣传画册
  • 抚州市临川区建设局网站公司排行榜
  • 信阳网站建设培训网站设计怎么做好
  • 空调维修网站模板深圳专业做网站电话
  • 有哪些网站是静态网站注册完域名怎么做网站
  • 团购营销型网站制作seo学徒是做什么
  • 汕头网站搜索优化江西宣传片制作公司
  • 昆明网站建设代理网站域名备案转接入手续
  • 陕西网站建设价格一个小程序开发费用
  • 长沙做网站要微联讯点很好简单的网站建设