tensorflow typeerror:未能将< class'tensorflow.python.framework.sparse\u tensor.sparsetensor'>类型的对象转换为tensor

aor9mmx1  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(310)

通过从头构建word2vec,尝试从word2vec的直观介绍运行代码时,我遇到了一个tensorflow错误:

x2
['like watching movie',
 'I watching movie',
 'I like movie',
 'I like watching',
 'enjoy watching movie',
 'I watching movie',
 'I enjoy movie',
 'I enjoy watching']

y2
['I', 'like', 'watching', 'movie', 'I', 'enjoy', 'watching', 'movie']

Transform the preceding input and output words into vectors.

vector_x = vectorizer.transform(x2)
vector_x.toarray()
array([[0, 0, 1, 1, 1],
       [0, 1, 0, 1, 1],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 0, 1],
       [1, 0, 0, 1, 1],
       [0, 1, 0, 1, 1],
       [1, 1, 0, 1, 0],
       [1, 1, 0, 0, 1]])

vector_y = vectorizer.transform(y2)
vector_y.toarray()
array([[0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 1, 0]])

import tensorflow
print(tensorflow.__version__)
2.4.1

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Embedding
from tensorflow.keras.layers import LSTM , Bidirectional,Dropout
from tensorflow.keras import backend as K

# from keras.layers.advanced_activations import LeakyReLU

from tensorflow.keras.layers import LeakyReLU
from tensorflow.keras import regularizers

model = Sequential()
model.add(Dense(3, activation='linear', input_shape=(5,)))
model.add(Dense(5,activation='sigmoid'))
model.summary()

Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_2 (Dense)              (None, 3)                 18        
_________________________________________________________________
dense_3 (Dense)              (None, 5)                 20        
=================================================================
Total params: 38
Trainable params: 38
Non-trainable params: 0

当我编译模型时,我得到一个错误:

model.compile(loss='binary_crossentropy',optimizer='adam')
model.fit(vector_x, vector_y, epochs=1000, batch_size=4,verbose=1)

...
...
...
    TypeError: Failed to convert object 
of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor. 
Contents: SparseTensor(indices=Tensor("DeserializeSparse_1:0", shape=(None, 2), dtype=int64), 
values=Tensor("DeserializeSparse_1:1", shape=(None,), dtype=int64), 
dense_shape=Tensor("stack_1:0", shape=(2,), dtype=int64)). Consider casting elements to a 
supported type.

这个示例代码是为旧版本的keras创建的。现在这个错误发生在最新稳定版本的TensorFlow2.4.1上。有什么想法吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题