将模型中的Tensor转为numpy

问题遇到的现象和发生背景

将tensor转换为numpy

用代码块功能插入代码,请勿粘贴截图
from keras import backend as K

in_shp = train_data.shape[1:]  # in_shap= (40962)
Xm_input = Input(in_shp)  
x1 = Lambda(slice,output_shape=(4096,1),arguments={'index':0})(Xm_input)
x2 = Lambda(slice,output_shape=(4096,1),arguments={'index':1})(Xm_input)
n1 = K.eval(x1)
model.compile(optimizer = Nadam(learning_rate=0.002),
loss= 'categorical_crossentropy',
metrics=[iou_coef],
run_eagerly=True)
运行结果及报错内容

('Some keys in session_kwargs are not supported at this time: %s', dict_keys(['run_eagerly']))

我的解答思路和尝试过的方法

想要将lambda层输出的Tensor转为numpy,刚开始会报placehold的错误,之后再compile中加了run_eagerly参数,又报了新的错误:('Some keys in session_kwargs are not supported at this time: %s', dict_keys(['run_eagerly']))

我想要达到的结果

将模型中的Tensor转为numpy

NumPy 数组转 Tensor:

import numpy as np
a = np.ones(7)
b = torch.from_numpy(a)
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)


[1. 1. 1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1., 1., 1.], dtype=torch.float64)
[2. 2. 2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2., 2., 2.], dtype=torch.float64)
[3. 3. 3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3., 3., 3.], dtype=torch.float64)


要把Tensor类型的数据变为numpy结构的数据可以参考下面的代码:
tensor.numpy()

试试
https://blog.csdn.net/weixin_38664232/article/details/104420283

把Tensor类型的数据变为numpy结构

tensor转为numpy格式

import torch as t
import numpy as np
 
x=t.ones(5).float()     #Tensor类型为FloatTensor,也可调用long()方法转为LongTensor
y=x.numpy()
print(x)
print(y)
 
##输出
tensor([1., 1., 1., 1., 1.])
[1. 1. 1. 1. 1.]