numpy 如何在Tensorflow中存储中间卷积结果

58wvjzkj  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(138)

请参考此链接中的"myalexnet_forward_tf2.py":
https://github.com/mikechen66/AlexNet_TensorFlow_2/tree/master/alexnet_original_tf2
在Alexnet中有5个回旋。
我想使用www.example.com()函数将单个中间卷积结果保存为. npy(无偏差相加)np.save() function
所以我添加如下代码:

def conv(input, kernel, biases, k_h, k_w, c_o, s_h, s_w, padding="VALID", group=1):
    '''From https://github.com/ethereon/caffe-tensorflow
    '''
    c_i = input.get_shape()[-1]
    assert c_i%group==0
    assert c_o%group==0
    convolve = lambda i,k: tf.nn.conv2d(i,k,[1,s_h,s_w,1],padding=padding)
    
    if group==1:
        conv = convolve(input, kernel)
    else:
        input_groups =  tf.split(input, group, 3)   #tf.split(3, group, input)
        kernel_groups = tf.split(kernel, group, 3)  #tf.split(3, group, kernel) 
        output_groups = [convolve(i, k) for i,k in zip(input_groups, kernel_groups)]
        conv = tf.concat(output_groups, 3)          #tf.concat(3, output_groups)
    
    np.save("conv_golden", conv) # <-------- added code    
    print("conv input shape :", input.shape, ", filter shape :", kernel.shape, ", conv result(no bias) shape :", conv.shape)
    return tf.reshape(tf.nn.bias_add(conv,biases), [-1]+conv.get_shape().as_list()[1:])

请查一下

np.save("conv_golden", conv) # <-------- added code

我只是希望卷积计算结果(conv)会自动保存。
当我执行这个命令时,错误消息显示"

NotImplementedError: Cannot convert a symbolic tf.Tensor (Conv2D:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported.

"
我对tensorflow的了解不够深入,但我猜tensorflow抽象了序列,当数据被放入时,序列就被执行了。
如何保存5个单独的中间卷积结果?

mf98qq94

mf98qq941#

此错误是预期错误。
如果不使用tf.compat.v1.disable_eager_execution(),只需对Tensor使用.numpy()方法,然后保存。

import numpy as np
import tensorflow as tf

# Create a sample tensor
x = tf.constant([[10, 2], [33, 4]], dtype=tf.float32)

# Convert to numpy
x_np = x.numpy()

# Save the numpy array to disk
np.save('x_saved.npy', x_np)

如果使用tf.compat.v1.disable_eager_execution(),请执行以下操作:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
import numpy as np

# Build the TensorFlow graph
a = tf.constant([10, 2, 3])
b = tf.constant([4, 5, 60])
c = tf.add(a, b)

# Create the session 
with tf.compat.v1.Session() as sess:
    x_saved = sess.run(c) # evaluate the tensor (this is the trick)

# Save the tensor
np.save("x_saved.npy", x_saved)

相关问题