如何将元素舍入功能应用于Keras Tensor?

时间:2018-04-28 18:25:41

标签: python tensorflow deep-learning keras

我正在尝试在Keras中编写Lambda样式的图层,将前一个1D密集(output_len)图层中的每个权重量化为最接近的1/128步。

我曾尝试在Keras后端使用map_tf函数,但到目前为止我没有运气。

基本上我尝试做的是将以下函数元素应用于1D输入张量:

def quantize(x):
    'Squashes x (0->1) to steps of 1/128'
    precision = 3
    base = 0.0078125 # 1/128
    if x < 0:
        x = 0
    elif x > 1:
        x = 1

    return round(base * round(float(x)/base) - 1/256, precision)

因此,例如,这将是某种预测的结果:

input (after going through the CNN):
  [0.21940812, 0.7998919 , 0.5420448 , 0.33850232 ]
output (after leaving the quantization layer):
  [0.215, 0.793, 0.535, 0.332 ]

我试图实现的目标是什么?

感谢。

1 个答案:

答案 0 :(得分:1)

我就是这样做的:

import UIKit

class ViewController: UIViewController {

var windowViewOrigin: CGPoint!

@IBOutlet weak var topImageView: UIImageView!
@IBOutlet weak var bottomImageView: UIImageView!
@IBOutlet weak var windowView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    addPanGesture(view: windowView)
    windowViewOrigin = windowView.frame.origin
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func addPanGesture(view: UIView){
    let pan = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePan(sender:)))
    view.addGestureRecognizer(pan)
}

@objc func handlePan(sender: UIPanGestureRecognizer){
    let window = sender.view!
    let translation = sender.translation(in: view)

    switch sender.state {
    case .began, .changed :
        windowView.center = CGPoint(x: UIScreen.main.bounds.size.width*0.5, y: window.center.y + translation.y)
        sender.setTranslation(CGPoint.zero, in: view)
        break
    case .ended:
        UIView.animate(withDuration: 0.5) {
            self.topImageView.alpha = 0.0
        }
        break
    default:
        break
    }
}
}

输出:

  

[[0.215 0.79300004 0.535 0.33200002]]

如果你能忍受舍入错误......