Python之数据分析(星期均值、星期汇总、Numpy的take与where方法、apply_along_axis函数)

一、处理星期数据

1、datetime对象的weekday()方法
该方法将会用0到6这七个数字表示周一到周日

2、计算周一到周五数据平均值的三种方法

  • 数组[关系表达式]:关系表达式的值是一个布尔型数组,其中为True的元素是数组中满足关系表达式的元素。以上下标运算的值就是从数组拣选与布尔数组中为True的元素相对于的元素。
  • np.where(关系表达式):数组中满足关系表达式的元素的下标数组
  • np.take(数组, 下标数组):数组中由下标数组所表示的元素的集合

3、按星期求均值案例

import numpy as np
import datetime as dt

# 将日期转换成天数
def dmy2week(dmy):
    dmy = str(dmy, encoding='utf-8')
    date = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
    wdays = date.weekday()  # 将日期变成星期的格式
    return wdays

# 解包取出日期、收盘价
wdays, closing_prices = np.loadtxt(
    '0=数据源/beer_price.csv', delimiter=',',
    usecols=(0, 4), unpack=True,
    converters={
   
   0: dmy2week}
)

# print(wdays)


# 计算周一到周五的平均值
ave_closing_prices = np.zeros(7)
for wday in range(ave_closing_prices.size):
    # 方法一:用掩码的方法
    # ave_closing_prices[wday] = \
  
### YOLO 中边界框融合 (WBF)方法 在目标检测领域,加权框融合(Weighted Boxes Fusion, WBF)是一种用于提高多模型或多尺度预测一致性的技术。相比于传统的非极大值抑制(NMS),WBF 能够更好地处理来自不同模型或同一模型的不同尺度下的冗余边界框问题[^3]。 #### 加权框融合的工作原理 WBF 方法通过综合考虑多个候选框的位置、置信度分数等因素,对这些候选框进行加权平均得到最终的预测结果。具体来说: - 对于每一个类别的所有候选框,按照其置信度得分赋予不同的权重; - 计算每个类别下所有候选框坐标的加权均值作为该类别的最终位置; - 同时也计算出一个新的置信度评分,这个评分为所有参融合的候选框置信度分的加权和再除以它们各自权重之和。 这种做法不仅能够减少因单个模型误检而产生的错误,还能够在一定程度上提升整体检测精度。 #### Python 实现代码示例 下面是一个简单的基于 PyTorch 和 NumPy 库实现 WBF 的例子: ```python import numpy as np def weighted_boxes_fusion(boxes_list, scores_list, labels_list, weights=None, iou_thr=0.55, skip_box_thr=0.0001): """ :param boxes_list: list of box arrays from different models/scales. Each element is a N x 4 array where each row contains [x_min, y_min, x_max, y_max]. :param scores_list: confidence score lists corresponding to the boxes. Should be same length with `boxes_list`. :param labels_list: label id lists for all predictions across multiple detectors/models. Also should match lengths between elements within this parameter and those inside both previous parameters. :param weights: optional weight vector used during fusion process; defaults None means equal weighting among inputs. :param iou_thr: IoU threshold when deciding whether two bounding boxes overlap enough so they can be merged into one single output. Default value set at 0.55 based on common practice but may vary depending upon dataset characteristics etc.. :param skip_box_thr: minimum required detection probability before considering any given prediction valid; very low detections will simply get ignored without affecting others' outcomes significantly. Returns fused bounding boxes along with updated probabilities after applying WBF algorithm over input data provided by user. """ # Ensure that we have consistent dimensions throughout our operation... assert isinstance(boxes_list, (list,tuple)), "Input must be either List or Tuple" num_models = len(boxes_list) if not weights: weights = np.ones((num_models), dtype=float)/float(num_models) # Initialize variables needed later down below while iterating through individual items per model/image pairings available here... final_bboxes = [] final_scores = [] unique_labels = sorted(set([item for sublist in labels_list for item in sublist])) for lbl in unique_labels: bbs_for_label = [] scs_for_label = [] for mdl_idx in range(len(labels_list)): mask = np.array(labels_list[mdl_idx]) == lbl filtered_boxes = np.asarray(boxes_list[mdl_idx])[mask].tolist() filtered_scores = np.asarray(scores_list[mdl_idx])[mask].tolist() wghtd_filtered_scores = [(score * weights[mdl_idx]) for score in filtered_scores] bbs_for_label.extend(filtered_boxes) scs_for_label.extend(wghtd_filtered_scores) indices_to_keep = nms(bbs_for_label, scs_for_label, iou_threshold=iou_thr) selected_bboxes = np.take(np.array(bbs_for_label), indices_to_keep, axis=0).tolist() selected_scores = np.take(np.array(scs_for_label), indices_to_keep, axis=0).tolist() combined_bbox_coords = sum(selected_bboxes)*weights.sum() / max(sum([wgt*sum(box) for box,wgt in zip(selected_bboxes,[weights[i]*len(list(filter(lambda x:x==lbl,labels)))for i,labels in enumerate(labels_list)])]),skip_box_thr) avg_score_per_class = sum(selected_scores)/(max(sum(weights),skip_box_thr)) final_bboxes.append(combined_bbox_coords.tolist()) final_scores.append(avg_score_per_class) return final_bboxes, final_scores def nms(dets, scores, iou_threshold): """Apply non-1] keep = [] suppressed = np.zeros_like(order,dtype=bool) for _i in range(len(order)): idx_i = order[_i] if suppressed[idx_i]: continue keep.append(idx_i) suppressed[[order[j] for j in range(_i+1,len(order)) if calc_iou(dets[idx_i], dets[order[j]]) >= iou_threshold]] = True return keep def calc_iou(bbox_a,bbox_b): """Calculate intersection-over-union ratio""" xa,ya,wa,ha=bbox_a[:];xb,yb,wb,hb=bbox_b[:] inter_xmin=max(xa,xb);inter_ymin=max(ya,yb); inter_xmax=min(xa+wa,xb+wb);inter_ymax=min(ya+ha,yb+hb); intersect_area=(max(inter_xmax-inter_xmin,0))*(max(inter_ymax-inter_ymin,0)) union_area=((xa-xb)*(ya-yb))+intersect_area-(intersect_area) return float(intersect_area/union_area) if __name__=='__main__': pass ``` 此函数实现了基本的 WBF 流程,并且包含了辅助功能如 NMS 来帮助去除高度重叠但仍需保留下来的高质量提案。注意这里的参数设置可以根据实际情况调整优化性能表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸿蒙Next

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值