在张量流中编写自定义成本函数 [英] writing a custom cost function in tensorflow

查看:87
本文介绍了在张量流中编写自定义成本函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在张量流中编写自己的成本函数,但是显然我无法切片"张量对象?

I'm trying to write my own cost function in tensor flow, however apparently I cannot 'slice' the tensor object?

import tensorflow as tf
import numpy as np

# Establish variables
x = tf.placeholder("float", [None, 3])
W = tf.Variable(tf.zeros([3,6]))
b = tf.Variable(tf.zeros([6]))

# Establish model
y = tf.nn.softmax(tf.matmul(x,W) + b)

# Truth
y_ = tf.placeholder("float", [None,6])

def angle(v1, v2):
  return np.arccos(np.sum(v1*v2,axis=1))

def normVec(y):
  return np.cross(y[:,[0,2,4]],y[:,[1,3,5]])

angle_distance = -tf.reduce_sum(angle(normVec(y_),normVec(y)))
# This is the example code they give for cross entropy
cross_entropy = -tf.reduce_sum(y_*tf.log(y))

我收到以下错误: TypeError: Bad slice index [0, 2, 4] of type <type 'list'>

推荐答案

目前,tensorflow 可以t在第一个以外的其他轴上聚集-已请求.

At present, tensorflow can't gather on axes other than the first - it's requested.

但是对于在这种特定情况下要执行的操作,可以转置,然后收集0、2、4,然后转回.它不会很快发疯,但它可以起作用:

But for what you want to do in this specific situation, you can transpose, then gather 0,2,4, and then transpose back. It won't be crazy fast, but it works:

tf.transpose(tf.gather(tf.transpose(y), [0,2,4]))

这是一个有用的解决方法,可以解决当前collect实施中的一些局限性.

This is a useful workaround for some of the limitations in the current implementation of gather.

(但是在tensorflow节点上不能使用numpy slice也是正确的-您可以运行它并对输出进行切片,并且还需要在运行之前初始化这些变量.:).您正在以无效的方式混合tf和np.

(But it is also correct that you can't use a numpy slice on a tensorflow node - you can run it and slice the output, and also that you need to initialize those variables before you run. :). You're mixing tf and np in a way that doesn't work.

x = tf.Something(...)

是张量流图对象. Numpy不知道如何应对此类对象.

is a tensorflow graph object. Numpy has no idea how to cope with such objects.

foo = tf.run(x)

又回到了python可以处理的对象.

is back to an object python can handle.

您通常希望将损失计算保持在纯张量流中,因此在tf中也要进行交叉和其他函数处理.您可能需要很长一段路来做arccos,因为tf没有它的功能.

You typically want to keep your loss calculation in pure tensorflow, so do the cross and other functions in tf. You'll probably have to do the arccos the long way, as tf doesn't have a function for it.

这篇关于在张量流中编写自定义成本函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆