TensorFlow模型变量重用

本文介绍了解决TensorFlow模型加载过程中出现的变量重用错误的方法。通过在Session中添加tf.get_variable_scope().reuse_variables(),可以避免VariableAlreadyExists错误,确保模型正确加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TensorFlow模型变量重用问题

加载模型及检测的.py
# predict.py

import numpy as np
import tensorflow as tf
from PIL import Image
import time

import fcrn

def predict(model_data_path, image_path , png_path):
    # Default input size
    height = 228
    width = 304
    channels = 3
    batch_size = 1
    
    # Read image
    try:
        img = Image.open(image_path)
    except:
        str1 = '无法打开图像'
        str2 = '请检查图像是否完整'
        return str1, str2

    img_format = img.format
    if img_format not in ['jpeg', 'JPEG']:
        str1 = '图像不是jpg格式'
        str2 = '请重新输入jpg图像'
        return str1, str2
    
    img = img.resize([width, height], Image.ANTIALIAS)
    img = np.array(img).astype('float32')
    img = np.expand_dims(np.asarray(img), axis=0)
   
    # Create a placeholder for the input image
    input_node = tf.placeholder(tf.float32, shape=(None, height, width, channels))
    
    # Construct the network
    net = fcrn.ResNet50UpProj({'data': input_node}, batch_size, 1, False)
        
    with tf.Session() as sess:
        # Load the converted parameters
        # print('Loading the model')

        # Use to load from ckpt file
        time1 = time.time()
        saver = tf.train.Saver()     
        saver.restore(sess, model_data_path)
        time2 = time.time()
        print('加载模型时间:', time2 - time1)

        # Use to load from npy file
        #net.load(model_data_path, sess) 

        # Evalute the network for the given image
        pred = sess.run(net.get_output(), feed_dict={input_node: img})

        max_depth = pred[0, :, :, 0].max()
        min_depth = pred[0, :, :, 0].min()

        # print(max_depth, min_depth)

        # 深度转灰度
        png_array = (pred[0, :, :, 0] - min_depth) / (max_depth - min_depth) * 255.0

        # 灰度转深度系数
        alpha = (max_depth - min_depth) / 255.0
        beta = min_depth

        # png_array = pred[0, :, :, 0] / max_depth * 255

        depth_png = Image.fromarray(np.uint8(png_array))
        depth_png.save(png_path)

        return alpha, beta
测试.py
import predict

model = './ckpt/NYU_FCRN.ckpt'

image_path1 = './test_image/test1.jpg'
png_path1 = './test1.png'

image_path2 = './test_image/test2.jpg'
png_path2 = './test2.png'

image_path3 = './test_image/test3.jpg'
png_path3 = './test3.png'

x, y = predict_new_new.predict(model, image_path1, png_path1)
print(x, y)
print('\n')


x, y = predict_new_new.predict(model, image_path2, png_path2)
print(x, y)
print('\n')


x, y = predict_new_new.predict(model, image_path3, png_path3)
print(x, y)
print('\n')

报错
ValueError: Variable conv1/weights already exists, disallowed.
 Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? 
 Originally defined at:
解决办法

在with tf.Session() as sess: 下面加一句
tf.get_variable_scope().reuse_variables()就行了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值