Python 作为神经网络输入的特征
这就是我定义神经网络的方式Python 作为神经网络输入的特征,python,tensorflow,Python,Tensorflow,这就是我定义神经网络的方式 import tensorflow as tf class MyFun: def __init__(self, x, y, sizes, activations, scope): with tf.variable_scope(scope): last_out = tf.concat([x, y], axis=1) for l, size in enumerate(sizes):
import tensorflow as tf
class MyFun:
def __init__(self, x, y, sizes, activations, scope):
with tf.variable_scope(scope):
last_out = tf.concat([x, y], axis=1)
for l, size in enumerate(sizes):
last_out = tf.layers.dense(last_out, size, activation=activations[l])
self.vars = tf.trainable_variables(scope=scope)
self.output = last_out
我需要将预处理输入x
和y
(两个占位符)输入到功能中,然后再将它们输入到网络中。更具体地说,我想使用二次特征,即
new_输入=[1,x,y,x**2,y**2,交叉(x,y)]
其中,交叉(x,y)
包括[x,y]
所有元素之间的乘积,即
cross(x,y)=[x_1*x_2,x_1*x_3,…,x_1*y_1,…]
我怎样才能做得优雅呢?是否有与sklearn.preprocessing.PolynomialFeatures等价的功能?这里有一个选项:
#假设占位符是一维向量,大小为3和7:
x=tf.placeholder(tf.float32,shape=[3])
y=tf.placeholder(tf.float32,shape=[7])
#concat常数为1.0,x和y为:
z=tf.concat((tf.constant(1.0,形状=(1,)),x,y),轴=0)
#构造成对的所有乘积:
新的_输入=[z[i]*z[j]表示范围(3+7-1)内的i,表示范围(i,3+7)内的j]
#将张量列表转换为张量(可选):
新输入=tf.stack(新输入)
编辑1 将此扩展到
x
和y
具有批次维度的情况:
x=tf.placeholder(tf.float32,shape=[None,3])
y=tf.placeholder(tf.float32,shape=[None,7])
#我使用1.0+0*x[:,:1]代替tf.constant(1.0)
z=tf.concat((1.0+0*x[:,:1],x,y),轴=1)
新的_输入=[z[:,i]*z[:,j]表示范围(3+7-1)内的i,表示范围(i,3+7)内的j]
新输入=tf.stack(新输入,1)
谢谢您的回答。但是,我的占位符x
和y
具有形状(?,常数)
,而不是(常数)
和tf。concat
给了我一个错误。我如何修复它?我更新了答案,尽管我承认这个解决方案不是很优雅。我希望它能解决你的问题。