简体   繁体   English

如何将 numpy 数组转换为 keras 张量

[英]how to convert numpy array to keras tensor

When using the keras model to do predict, I got the error below使用keras模型进行预测时,出现以下错误

AttributeError: 'Tensor' object has no attribute 'ndim' AttributeError: 'Tensor' 对象没有属性 'ndim'

The reason is that the weights is numpy array, not tensor.原因是权重是 numpy 数组,而不是张量。
So how to convert numpy array to keras tensor?那么如何将 numpy 数组转换为 keras 张量呢?

In Tensorflow it can be done the following way:在 Tensorflow 中,它可以通过以下方式完成:

import tensorflow.keras.backend as K
import numpy as np

a = np.array([1,2,3])
b = K.constant(a)
print(b)

# <tf.Tensor 'Const_1:0' shape=(3,) dtype=float32>

print(K.eval(b))

# array([1., 2., 3.], dtype=float32)

In raw keras it should be done replacing import tensorflow.keras.backend as K with from keras import backend as K .在原始 keras 中,应该将import tensorflow.keras.backend as K替换import tensorflow.keras.backend as K from keras import backend as K

To convert numpy array to tensor,要将 numpy 数组转换为张量,

import tensor as tf
#Considering y variable holds numpy array
y_tensor = tf.convert_to_tensor(y, dtype=tf.int64) 

#You can use any of the available datatypes that suits best - https://www.tensorflow.org/api_docs/python/tf/dtypes/DType #您可以使用任何最适合的可用数据类型 - https://www.tensorflow.org/api_docs/python/tf/dtypes/DType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM