我们可以在python脚本中动态更改tensorflow版本吗?

2024-10-01 02:36:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个旧的python脚本(tf-1.15.2),需要在TensorFlow-2.2.0中运行(不能使用tf<;2.2),我已经将大部分代码迁移到了tf-2.2.0,但是代码中使用了一些与TensorFlow.contrib相关的方法。因此,我想使用旧版本tf-1.15来运行那些使用tensorflow.contrib相关API的代码行

所以,现在的问题是我已经在全球安装了tf-1.15.2,在本地安装了tf-2.2.0。但是,在python进程运行时,如何在特定的时间点访问TensorFlow的特定版本呢

下面是示例代码

import tensorflow as tf             # version: tf-2.2.0 (local package is imported)
isess = tf.compat.v1.Session()
tf.compat.v1.disable_eager_execution()
​
# Creatoin of the required placeholders
p = []
for shape in input_shapes:
    p.append(tf.compat.v1.placeholder(shape=shape, dtype=input_dtype))
out = tf.einsum(equation, *p)
graph_def = isess.graph_def         
# TODO
# To feed this (graph_def, feed_dict, output_tensors) to a session object of tf-1.15.2 and find the output

现在,在用适当的函数(trace/dot_product/…)替换einsum之后,为了测试tf_1.15.2中的tf_einsum_op_test中给出的单元测试,我想返回tf-1.15.2并检查执行情况

潜在的需求是确定在python进程的执行流中是否可以交换tf版本。考虑Einsum op,因为tf-1.15.2中未直接支持它


Tags: of代码版本进程tftensorflowdefcontrib
1条回答
网友
1楼 · 发布于 2024-10-01 02:36:13

在试验子流程API之后,我发现在python流程执行期间,可以通过子流程调用在tf版本之间切换

# main.py
import tensorflow as tf             # version: tf-2.2.0 (local package is imported)
import subprocess
import os
isess = tf.compat.v1.Session()
tf.compat.v1.disable_eager_execution()
​
# Creatoin of the required placeholders
p = []
for shape in input_shapes:
    p.append(tf.compat.v1.placeholder(shape=shape, dtype=input_dtype))
out = tf.einsum(equation, *p)
graph_def = isess.graph_def
#TODO: Save the graph_def in graph.pb
#TODO: Save the feed_dict in input.npz
#TODO: Save the output_tensors

#Change the python path to the global package
os.environ['PYTHONPATH'] = '/usr/local/lib/python3.6/dist-packages'
cmd = ['python3.6','run.py']
out = subprocess.check_output(cmd)         #Subprocess call
#run.py
import tensorflow as tf            # version: tf-1.15.2 (global package is imported)
import numpy as np
#TODO: Load the graphdef from graph.pb
#TODO: Load the feed_dict from input.npz
#TODO: Load the output tensors
g = tf.import_graph_def(graph_def,name='')
with tf.Session(graph=g) as sess:
    output = sess.run(output_tensors,feed_dict)

这对我有用

相关问题 更多 >