本文主要是介绍Kmeans 算法 修改 anchor,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
新建文件 kmeans.py
import numpy as npdef iou(box, clusters):"""Calculates the Intersection over Union (IoU) between a box and k clusters.:param box: tuple or array, shifted to the origin (i. e. width and height):param clusters: numpy array of shape (k, 2) where k is the number of clusters:return: numpy array of shape (k, 0) where k is the number of clusters"""x = np.minimum(clusters[:, 0], box[0])y = np.minimum(clusters[:, 1], box[1])if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:raise ValueError("Box has no area")intersection = x * ybox_area = box[0] * box[1]cluster_area = clusters[:, 0] * clusters[:, 1]iou_ = intersection / (box_area + cluster_area - intersection)return iou_def avg_iou(boxes, clusters):"""Calculates the average Intersection over Union (IoU) between a numpy array of boxes and k clusters.:param boxes: numpy array of shape (r, 2), where r is the number of rows:param clusters: numpy array of shape (k, 2) where k is the number of clusters:return: average IoU as a single float"""return np.mean([np.max(iou(boxes[i], clusters)) for i in range(boxes.shape[0])])def translate_boxes(boxes):"""Translates all the boxes to the origin.:param boxes: numpy array of shape (r, 4):return: numpy array of shape (r, 2)"""new_boxes = boxes.copy()for row in range(new_boxes.shape[0]):new_boxes[row][2] = np.abs(new_boxes[row][2] - new_boxes[row][0])new_boxes[row][3] = np.abs(new_boxes[row][3] - new_boxes[row][1])return np.delete(new_boxes, [0, 1], axis=1)def kmeans(boxes, k, dist=np.median):"""Calculates k-means clustering with the Intersection over Union (IoU) metric.:param boxes: numpy array of shape (r, 2), where r is the number of rows:param k: number of clusters:param dist: distance function:return: numpy array of shape (k, 2)"""rows = boxes.shape[0]distances = np.empty((rows, k))last_clusters = np.zeros((rows,))np.random.seed()# the Forgy method will fail if the whole array contains the same rowsclusters = boxes[np.random.choice(rows, k, replace=False)]while True:for row in range(rows):distances[row] = 1 - iou(boxes[row], clusters)nearest_clusters = np.argmin(distances, axis=1)if (last_clusters == nearest_clusters).all():breakfor cluster in range(k):clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0)last_clusters = nearest_clustersreturn clusters
新建文件 example.py
import glob
import xml.etree.ElementTree as ETimport numpy as npfrom kmeans import kmeans, avg_iouANNOTATIONS_PATH = "path/Annotations"
CLUSTERS = 9def load_dataset(path):dataset = []for xml_file in glob.glob("{}/*xml".format(path)):tree = ET.parse(xml_file)height = int(tree.findtext("./size/height"))width = int(tree.findtext("./size/width"))for obj in tree.iter("object"):xmin = int(obj.findtext("bndbox/xmin")) / widthymin = int(obj.findtext("bndbox/ymin")) / heightxmax = int(obj.findtext("bndbox/xmax")) / widthymax = int(obj.findtext("bndbox/ymax")) / heightdataset.append([xmax - xmin, ymax - ymin])return np.array(dataset)data = load_dataset(ANNOTATIONS_PATH)
out = kmeans(data, k=CLUSTERS)
print("Accuracy: {:.2f}%".format(avg_iou(data, out) * 100))
# print("Boxes:\n {}".format(out))
# print("Boxes:\n {}-{}".format(out[:, 0], out[:, 1]))
print(out[:, 0] / out[:, 1])ratios = np.around(out[:, 0] / out[:, 1], decimals=2).tolist()
print("Ratios:\n {}".format(sorted(ratios)))
输出如下:
Accuracy: 88.11%
[0.88394192 0.73313783 0.73044577 0.76032522 0.70908138 0.76894224 0.75933618 0.77438715 0.79756781]
Ratios: [0.71, 0.73, 0.73, 0.76, 0.76, 0.77, 0.77, 0.8, 0.88]
最大值是0.8839, 最小值是0.7090。
在这里我们继续使用faster rcnn中的base_size=16这一设定
原始论文中,ratios=[0.5, 1, 2]。在这里ratios=[0.8, 1, 1.25],0.8=0.7090/0.8839,1.25=0.8839/0.7090
原始论文中 scales=2**np.arange(3, 6)=(6, 8, 10),在这里根据输入图片的尺度,结合进行修改。
这篇关于Kmeans 算法 修改 anchor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!