标签: quantization

OpenCV量化示例代码未运行

我正在运行OpenCV文档中的量化示例代码,它正在抛出

Traceback (most recent call last):
File "QuantizeTest.py", line 13, in <module>
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
TypeError: an integer is required
Run Code Online (Sandbox Code Playgroud)

这是代码本身:

import numpy as np
import cv2

img = cv2.imread('Sample.jpg')
Z = img.reshape((-1,3))

# convert to np.float32
Z = np.float32(Z)

# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 8
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))

cv2.imshow('res2',res2) …
Run Code Online (Sandbox Code Playgroud)

python opencv quantization k-means

4
推荐指数
1
解决办法
1339
查看次数

量化(减少图像色彩)

我正在尝试使用C#将图像量化为10种颜色,绘制量化图像时遇到问题,我制作了映射表,并且它是正确的,我制作了原始图像的副本,并且正在更改基于映射表的像素,我正在使用以下代码:

bm = new Bitmap(pictureBox1.Image);
        Dictionary<Color, int> histo = new Dictionary<Color, int>();
        for (int x = 0; x < bm.Size.Width; x++)
            for (int y = 0; y < bm.Size.Height; y++)
            {
                Color c = bm.GetPixel(x, y);
                if (histo.ContainsKey(c))
                    histo[c] = histo[c] + 1;
                else
                    histo.Add(c, 1);
            }
        var result1 = histo.OrderByDescending(a => a.Value);
                  int ind = 0;
        List<Color> mostusedcolor = new List<Color>();
        foreach (var entry in result1)
        {
            if (ind < 10)
            {
                mostusedcolor.Add(entry.Key);
                ind++;
            }
            else
                break;
        }
        Double …
Run Code Online (Sandbox Code Playgroud)

c# quantization

4
推荐指数
1
解决办法
945
查看次数

Tensorflow构建量化工具 - bazel构建错误

我正在尝试编译Pete Warden博客中描述的量化脚本.但是,运行以下bazel构建后,我收到以下错误消息:

bazel build tensorflow/contrib/quantization/tools:quantize_graph
ERROR: no such package 'tensorflow/contrib/quantization/tools': BUILD       file not found on package path.
INFO: Elapsed time: 0.277s
Run Code Online (Sandbox Code Playgroud)

quantization deep-learning bazel tensorflow

4
推荐指数
1
解决办法
1774
查看次数

如何计算聚类的量化误差?

我想使用量化误差来测量聚类的质量,但找不到有关如何计算此指标的任何明确信息。

我发现的少数文件/文章是:

关于第三个链接(这是迄今为止我找到的最好的信息),我不知道如何解释计算(参见下面的代码片段):

(# 注释是我的。问号表示我不清楚的步骤)

def quantization_error(self):
        """
        This method calculates the quantization error of the given clustering
        :return: the quantization error
        """
        total_distance = 0.0
        s = Similarity(self.e) #Class containing different types of distance measures

        #For each point, compute squared fractional distance between point and centroid ?
        for i in range(len(self.solution.patterns)): 
            total_distance += math.pow(s.fractional_distance(self.solution.patterns[i], self.solution.centroids[self.solution.solution[i]]), 2.0)

        return total_distance / len(self.solution.patterns) # Divide total_distance by the total …
Run Code Online (Sandbox Code Playgroud)

python cluster-analysis quantization

4
推荐指数
1
解决办法
2696
查看次数

tf.fake_quant_with_min_max_args 和 tf.fake_quant_with_min_max_vars 有什么区别

我很想了解张量流函数之间的差异

tf.fake_quant_with_min_max_args
tf.fake_quant_with_min_max_vars
Run Code Online (Sandbox Code Playgroud)

正如他们的 API 中一样,它们的描述几乎相同。我通常通过手动量化所需的节点tf.fake_quant_with_min_max_vars,尽管我不确定它是否正确。

例如,权重应该使用 吗tf.fake_quant_with_min_max_args

同样,查看 的代码quantize.Quantize,我确实明白它基本上会迭代图形,找到兼容的张量并根据 global_step 添加用于身份/量化的节点。但是,我是否应该理解并非所有操作都是量化的(例如 conv1d,尽管 conv2d 和 mat/mul 是量化的)。图书馆以后会支持所有的操作吗?

python quantization tensorflow

4
推荐指数
1
解决办法
1820
查看次数

Tensorflow 量子化 - 零点是什么意思

我正在尝试了解张量流中的量化,并且正在遵循本教程。

\n\n

https://heartbeat.fritz.ai/8-bit-quantization-and-tensorflow-lite-speeding-up-mobile-inference-with-low- precision-a882dfcafbbd

\n\n

在教程中它说,量化方程是:

\n\n

在此输入图像描述

\n\n
    \n
  • r 是实际值(通常是 float32)
  • \n
  • q 是 B 位整数(uint8、uint32 等)的量化表示
  • \n
  • S (float32) 和 z (uint) 是我们缩放和移动数轴的因子。z 是量化的 \xe2\x80\x98zero-point\xe2\x80\x99 ,它将始终精确地映射回 0.f。
  • \n
\n\n

我正在努力理解零点的含义,希望有人能用一个例子来解释它?

\n

quantization tensorflow

4
推荐指数
1
解决办法
4424
查看次数

如何确保 TFLite 解释器仅使用 int8 运算?

我一直在使用 Tensorflow 的 TFLite 研究量化。据我了解,可以量化我的模型权重(以便使用更少的 4 倍内存来存储它们),但这并不一定意味着模型不会将其转换回浮点数来运行它。我还了解到,要仅使用 int 运行我的模型,我需要设置以下参数:

converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
Run Code Online (Sandbox Code Playgroud)

我想知道tf.lite.Interpreter设置了这些参数的加载模型与未设置这些参数的加载模型之间有什么区别。我试图对此进行调查.get_tensor_details(),但没有发现任何差异。

python quantization keras tensorflow tensorflow-lite

4
推荐指数
1
解决办法
4957
查看次数

在 pytorch 中使用量化模型没有性能提升

我在 pytorch 中用 float 数据类型训练了一个模型。我想通过将此模型转换为量化模型来缩短推理时间。我使用torch.quantization.convert api 将模型的权重转换为 uint8 数据类型。然而,当我使用这个模型进行推理时,我没有得到任何性能改进。我在这里做错了什么吗?

Unet模型代码:

def gen_initialization(m):
    if type(m) == nn.Conv2d:
        sh = m.weight.shape
        nn.init.normal_(m.weight, std=math.sqrt(2.0 / (sh[0]*sh[2]*sh[3])))
        nn.init.constant_(m.bias, 0)
    elif type(m) == nn.BatchNorm2d:
        nn.init.constant_(m.weight, 1)
        nn.init.constant_(m.bias, 0)

class TripleConv(nn.Module):
    def __init__(self, in_ch, out_ch):
        super(TripleConv, self).__init__()
        mid_ch = (in_ch + out_ch) // 2
        self.conv = nn.Sequential(
            nn.Conv2d(in_ch, mid_ch, kernel_size=3, stride=1, padding=1, bias=True),
            nn.BatchNorm2d(num_features=mid_ch),
            nn.LeakyReLU(negative_slope=0.1),
            nn.Conv2d(mid_ch, mid_ch, kernel_size=3, stride=1, padding=1, bias=True),
            nn.BatchNorm2d(num_features=mid_ch),
            nn.LeakyReLU(negative_slope=0.1),
            nn.Conv2d(mid_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),
            nn.BatchNorm2d(num_features=out_ch),
            nn.LeakyReLU(negative_slope=0.1)
        )
        self.conv.apply(gen_initialization)

    def forward(self, …
Run Code Online (Sandbox Code Playgroud)

python performance quantization deep-learning pytorch

3
推荐指数
1
解决办法
1367
查看次数

有没有办法将 quint8 pytorch 格式转换为 np.uint8 格式?

我使用下面的代码在 pytorch 中获取量化的 unsiged int 8 格式。但是,我无法将quant变量转换为 to np.uint8。有可能这样做吗?

import torch

quant = torch.quantize_per_tensor(torch.tensor([-1.0, 0.352, 1.321, 2.0]), 0.1, 10, torch.quint8)
Run Code Online (Sandbox Code Playgroud)

python quantization pytorch

3
推荐指数
1
解决办法
2932
查看次数

如何在 Python 解释器中提供多个输入 TFlite 模型

如何在 tflite 模型中提供 2 个输入。

我建立了一个 tf 模型 => 转换为 tflite

text = tf.keras.Input((64), name="text")
intent = tf.keras.Input(shape=(25,), name="intent")

layer = tf.keras.layers.Embedding(dataset.vocab_size, 128, name="embedding_layer")(text)
layer = tf.keras.layers.LocallyConnected1D(256, kernel_size=1, strides=1, padding="valid", activation="relu")(layer)
layer = tf.keras.layers.SpatialDropout1D(0.1)(layer)
layer = tf.keras.layers.GlobalAveragePooling1D()(layer)
layer = tf.keras.layers.Dense(512, activation="relu")(layer)
layer = tf.keras.layers.Dropout(0.1)(layer)

layer = tf.keras.layers.concatenate([layer, intent])

output_layer = tf.keras.layers.Dense(units=dataset.max_labels, activation="softmax")(layer)

model = tf.keras.models.Model(inputs=[text, intent], outputs=[output_layer])
Run Code Online (Sandbox Code Playgroud)

我的模型有 2 个输入。

interpreter.get_input_details():
[{'name': 'text',
  'index': 0,
  'shape': array([ 1, 64], dtype=int32),
  'shape_signature': array([ 1, 64], dtype=int32),
  'dtype': numpy.float32,
  'quantization': (0.0, 0), …
Run Code Online (Sandbox Code Playgroud)

python quantization tensorflow tensorflow-lite

3
推荐指数
1
解决办法
3727
查看次数