如何将 numpy 数组转换为 keras 张量 [英] how to convert numpy array to keras tensor

查看:58
本文介绍了如何将 numpy 数组转换为 keras 张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用keras模型进行预测时,出现以下错误

When using the keras model to do predict, I got the error below

AttributeError: 'Tensor' 对象没有属性 'ndim'

AttributeError: 'Tensor' object has no attribute 'ndim'

原因是权重是numpy数组,而不是张量.
那么如何将 numpy 数组转换为 keras 张量?

The reason is that the weights is numpy array, not tensor.
So how to convert numpy array to keras tensor?

推荐答案

在 Tensorflow 中可以通过以下方式完成:

In Tensorflow it can be done the following way:

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)

在原始 keras 中,应该将 import tensorflow.keras.backend as K 替换为 from keras import backend as K.

In raw keras it should be done replacing import tensorflow.keras.backend as K with from keras import backend as K.

这篇关于如何将 numpy 数组转换为 keras 张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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