当我在Keras / tensorflow 2.0中更改嵌入层中的参数时,了解嵌入的输出和错误消息

我正在尝试理解和熟悉嵌入。

我创建了一个由5个数据集组成的5000个观察值的人工数据集:

  1. 从均值= 1,标准差= 0.1的正态分布中提取的1000个值的样本

  2. 从均值= 5,标准差= 0.1的正态分布中提取的1000个值的样本

  3. 从均值= 7,标准差= 0.1的正态分布中提取的1000个值的样本

  4. 从均值= 1,标准差= 1的正态分布中提取的1000个值的样本

  5. 从均值= 7,标准差= 1的正态分布中提取的1000个值的样本

代码如下:

from scipy.stats import norm

y1 = norm.rvs(loc=1,scale=.1,size=1000)

y2 = norm.rvs(loc=5,size=1000)

y3 = norm.rvs(loc=7,size=1000)

y4 = norm.rvs(loc=5,scale= 1,size=1000)

y5 = norm.rvs(loc=1,size=1000)

df1 = pd.DataFrame({'x' : 1,'y': y1 })

df2 = pd.DataFrame({'x' : 2,'y': y2 })

df3 = pd.DataFrame({'x' : 3,'y': y3 })

df4 = pd.DataFrame({'x' : 4,'y': y4 })

df5 = pd.DataFrame({'x' : 5,'y': y5 })

df = pd.concat([df1,df2,df3,df4,df5],axis = 0)

df= df.sample(frac=1)

当我在Keras / tensorflow 2.0中更改嵌入层中的参数时,了解嵌入的输出和错误消息

我的目的是使用嵌入来表示代表二维空间中5个数据集(即1、2、3、4、5)的代码值。

我很想知道这种表示形式是否会以某种方式反映每个数据集的内部性质,即它们都是从正态分布中抽取的样本,但均值和标准差有5种不同的组合。

我的处理方式如下:

inputs = Input(shape=(1,))

x1 = Embedding(6,2,input_length=1,name = 'embeddings')(inputs)

x2 = flatten()(x1)

x3 = Dense(10,activation = 'relu')(x2)

x4 = Dense(10,activation = 'relu')(x3)

x5 = Dropout(0.5)(x4)

prediction = Dense(1)(x5)

model = Model(inputs = inputs,outputs = prediction)

model.compile(optimizer='Adam',loss='mse',metrics=['mae'])

model.fit(x = df.x.values,y = df.y.values,epochs = 10,batch_size = 16)  

然后我提取训练后的图层的权重并进行检查:

for layer in model.layers:

    if layer.name == 'embeddings':

        embedding_layer = layer

当我在Keras / tensorflow 2.0中更改嵌入层中的参数时,了解嵌入的输出和错误消息

所以在这里,我们有一个6行的矩阵,对应于输入的唯一值,如我们所见,它们是{1、2、3、4、5}。

但是哪一行对应于哪个值?

第六行“冗余”对应于什么?

您能提供对特定重量的直观解释吗?

如果这对您有帮助,我可以画出权重,因为它们是在2D空间中表示的。

ax = embeddings_df.reset_index().plot.scatter(x = 'x',y = 'y')
for i,txt in enumerate(embeddings_df.index):
    ax.annotate(txt,(embeddings_df.x.iat[i],embeddings_df.y.iat[i]))

当我在Keras / tensorflow 2.0中更改嵌入层中的参数时,了解嵌入的输出和错误消息

实际上,唯一输入值似乎对应于权重矩阵的各个索引。嵌入向量的位置似乎与生成分布的平均值有关(沿着从左上角高到右下角的对角线)。尽管尚不清楚映射的工作原理,但std的差异沿水平轴的位置不同。

一般而言,尽管我们如何知道权重矩阵的哪一行对应于输入向量中的唯一值?总是1对应权重矩阵的索引为1的行吗?

索引为0的行的作用是什么?

事实上,我尝试使用数字5作为嵌入数字来创建嵌入,该数字在拟合期间导致错误:

Train on 5000 samples
Epoch 1/10
  16/5000 [..............................] - eta: 2:53
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-44-ec152436476c> in <module>
----> 1 model.fit(x = df.x.values,batch_size = 16)

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\keras\engine\training.py in fit(self,x,y,batch_size,epochs,verbose,callbacks,validation_split,validation_data,shuffle,class_weight,sample_weight,initial_epoch,steps_per_epoch,validation_steps,validation_freq,max_queue_size,workers,use_multiprocessing,**kwargs)
    726         max_queue_size=max_queue_size,727         workers=workers,--> 728         use_multiprocessing=use_multiprocessing)
    729 
    730   def evaluate(self,~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in fit(self,model,**kwargs)
    322                 mode=ModeKeys.TRAIN,323                 training_context=training_context,--> 324                 total_epochs=epochs)
    325             cbks.make_logs(model,epoch_logs,training_result,ModeKeys.TRAIN)
    326 

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py in run_one_epoch(model,iterator,execution_function,dataset_size,strategy,num_samples,mode,training_context,total_epochs)
    121         step=step,mode=mode,size=current_batch_size) as batch_logs:
    122       try:
--> 123         batch_outs = execution_function(iterator)
    124       except (StopIteration,errors.OutOfRangeError):
    125         # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py in execution_function(input_fn)
     84     # `numpy` translates Tensors to values in Eager mode.
     85     return nest.map_structure(_non_none_constant_value,---> 86                               distributed_function(input_fn))
     87 
     88   return execution_function

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\eager\def_function.py in __call__(self,*args,**kwds)
    455 
    456     tracing_count = self._get_tracing_count()
--> 457     result = self._call(*args,**kwds)
    458     if tracing_count == self._get_tracing_count():
    459       self._call_counter.called_without_tracing()

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\eager\def_function.py in _call(self,**kwds)
    518         # lifting succeeded,so variables are initialized and we can run the
    519         # stateless function.
--> 520         return self._stateless_fn(*args,**kwds)
    521     else:
    522       canon_args,canon_kwds = \

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\eager\function.py in __call__(self,**kwargs)
   1821     """Calls a graph function specialized to the inputs."""
   1822     graph_function,args,kwargs = self._maybe_define_function(args,kwargs)
-> 1823     return graph_function._filtered_call(args,kwargs)  # pylint: disable=protected-access
   1824 
   1825   @property

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\eager\function.py in _filtered_call(self,kwargs)
   1139          if isinstance(t,(ops.Tensor,1140                            resource_variable_ops.BaseResourceVariable))),-> 1141         self.captured_inputs)
   1142 
   1143   def _call_flat(self,captured_inputs,cancellation_manager=None):

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\eager\function.py in _call_flat(self,cancellation_manager)
   1222     if executing_eagerly:
   1223       flat_outputs = forward_function.call(
-> 1224           ctx,cancellation_manager=cancellation_manager)
   1225     else:
   1226       gradient_name = self._delayed_rewrite_functions.register()

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\eager\function.py in call(self,ctx,cancellation_manager)
    509               inputs=args,510               attrs=("executor_type",executor_type,"config_proto",config),--> 511               ctx=ctx)
    512         else:
    513           outputs = execute.execute_with_cancellation(

~\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\eager\execute.py in quick_execute(op_name,num_outputs,inputs,attrs,name)
     65     else:
     66       message = e.message
---> 67     six.raise_from(core._status_to_exception(e.code,message),None)
     68   except TypeError as e:
     69     keras_symbolic_tensors = [

~\Anaconda3\envs\tf2\lib\site-packages\six.py in raise_from(value,from_value)

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument:  indices[1,0] = 5 is not in [0,5)
     [[node model_4/embeddings/embedding_lookup (defined at C:\Users\Alienware\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\framework\ops.py:1751) ]]
     [[Adam/Adam/update/AssignSubVariableOp/_39]]
  (1) Invalid argument:  indices[1,5)
     [[node model_4/embeddings/embedding_lookup (defined at C:\Users\Alienware\Anaconda3\envs\tf2\lib\site-packages\tensorflow_core\python\framework\ops.py:1751) ]]
0 successful operations.
0 derived errors ignored. [Op:__inference_distributed_function_33376]

Function call stack:
distributed_function -> distributed_function

这使我感到困惑,因为实际上输入的维数为5,因为我有5个以向量形式表示的不同/唯一值。

您能解释一下吗?

dangfangxia 回答:当我在Keras / tensorflow 2.0中更改嵌入层中的参数时,了解嵌入的输出和错误消息

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3146520.html

大家都在问