当前位置: 首页>>代码示例>>Python>>正文


Python tensorflow.InteractiveSession方法代码示例

本文整理汇总了Python中tensorflow.InteractiveSession方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.InteractiveSession方法的具体用法?Python tensorflow.InteractiveSession怎么用?Python tensorflow.InteractiveSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tensorflow的用法示例。


在下文中一共展示了tensorflow.InteractiveSession方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: omniglot

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def omniglot():

    sess = tf.InteractiveSession()

    """    def wrapper(v):
        return tf.Print(v, [v], message="Printing v")

    v = tf.Variable(initial_value=np.arange(0, 36).reshape((6, 6)), dtype=tf.float32, name='Matrix')

    sess.run(tf.global_variables_initializer())
    sess.run(tf.local_variables_initializer())

    temp = tf.Variable(initial_value=np.arange(0, 36).reshape((6, 6)), dtype=tf.float32, name='temp')
    temp = wrapper(v)
    #with tf.control_dependencies([temp]):
    temp.eval()
    print 'Hello'"""

    def update_tensor(V, dim2, val):  # Update tensor V, with index(:,dim2[:]) by val[:]
        val = tf.cast(val, V.dtype)
        def body(_, (v, d2, chg)):
            d2_int = tf.cast(d2, tf.int32)
            return tf.slice(tf.concat_v2([v[:d2_int],[chg] ,v[d2_int+1:]], axis=0), [0], [v.get_shape().as_list()[0]])
        Z = tf.scan(body, elems=(V, dim2, val), initializer=tf.constant(1, shape=V.get_shape().as_list()[1:], dtype=tf.float32), name="Scan_Update")
        return Z 
开发者ID:hmishra2250,项目名称:NTM-One-Shot-TF,代码行数:27,代码来源:TestUpd.py

示例2: get_tags_from_event

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def get_tags_from_event(filename):
    sess = tf.InteractiveSession()
    i = 0;
    tags = [];
    with sess.as_default():
        for event in tf.train.summary_iterator(filename):
            if (i==0):
                printed = 0;
                for val in event.summary.value:
                    print(val.tag)
                    tags.append[val.tag]
                    printed = 1
                if (printed):
                    i = 1
            else:
                break;
    return tags 
开发者ID:akshaysubr,项目名称:TEGAN,代码行数:19,代码来源:readTFevents.py

示例3: read_images_data_from_event

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def read_images_data_from_event(filename, tag):
    
    image_str = tf.placeholder(tf.string)
    image_tf = tf.image.decode_image(image_str)

    image_list = [];
    
    sess = tf.InteractiveSession()
    with sess.as_default():
        count = 0
        for event in tf.train.summary_iterator(filename):
            for val in event.summary.value:
                if val.tag == tag:
                    im = image_tf.eval({image_str: val.image.encoded_image_string})
                    image_list.append(im)
                    count += 1

        return image_list 
开发者ID:akshaysubr,项目名称:TEGAN,代码行数:20,代码来源:readTFevents.py

示例4: save_images_from_event

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def save_images_from_event(filename, tag, output_dir='./'):
    assert(os.path.isdir(output_dir))

    image_str = tf.placeholder(tf.string)
    image_tf = tf.image.decode_image(image_str)

    sess = tf.InteractiveSession()
    with sess.as_default():
        count = 0
        for event in tf.train.summary_iterator(filename):
            for val in event.summary.value:
                if val.tag == tag:
                    im = image_tf.eval({image_str: val.image.encoded_image_string})
                    output_fn = os.path.realpath('{}/image_{}_{:05d}.png'.format(output_dir, tag, count))
                    print("Saving '{}'".format(output_fn))
                    scipy.misc.imsave(output_fn, im)
                    count += 1
    return 
开发者ID:akshaysubr,项目名称:TEGAN,代码行数:20,代码来源:readTFevents.py

示例5: main

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def main(_):

  # Create the model and load its weights.
  sess = tf.InteractiveSession()
  create_inference_graph(FLAGS.wanted_words, FLAGS.sample_rate,
                         FLAGS.clip_duration_ms, FLAGS.clip_stride_ms,
                         FLAGS.window_size_ms, FLAGS.window_stride_ms,
                         FLAGS.dct_coefficient_count, FLAGS.model_architecture)
  models.load_variables_from_checkpoint(sess, FLAGS.start_checkpoint)

  # Turn all the variables into inline constants inside the graph and save it.
  frozen_graph_def = graph_util.convert_variables_to_constants(
      sess, sess.graph_def, ['labels_softmax'])
  tf.train.write_graph(
      frozen_graph_def,
      os.path.dirname(FLAGS.output_file),
      os.path.basename(FLAGS.output_file),
      as_text=False)
  tf.logging.info('Saved frozen graph to %s', FLAGS.output_file) 
开发者ID:nesl,项目名称:adversarial_audio,代码行数:21,代码来源:freeze.py

示例6: __init__

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def __init__(self, image_height, image_width, image_depth, channels=1, costname=("dice coefficient",),
                 inference=False, model_path=None):
        self.image_width = image_width
        self.image_height = image_height
        self.image_depth = image_depth
        self.channels = channels

        self.X = tf.placeholder("float", shape=[None, self.image_depth, self.image_height, self.image_width,
                                                self.channels])
        self.Y_gt = tf.placeholder("float", shape=[None, self.image_depth, self.image_height, self.image_width,
                                                   self.channels])
        self.lr = tf.placeholder('float')
        self.phase = tf.placeholder(tf.bool)
        self.drop = tf.placeholder('float')

        self.Y_pred = _create_conv_net(self.X, self.image_depth, self.image_width, self.image_height, self.channels,
                                       self.phase, self.drop)
        self.cost = self.__get_cost(costname[0])
        self.accuracy = -self.__get_cost(costname[0])
        if inference:
            init = tf.global_variables_initializer()
            saver = tf.train.Saver()
            self.sess = tf.InteractiveSession()
            self.sess.run(init)
            saver.restore(self.sess, model_path) 
开发者ID:junqiangchen,项目名称:LiTS---Liver-Tumor-Segmentation-Challenge,代码行数:27,代码来源:model_vnet3d.py

示例7: __init__

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def __init__(self, action_size):
        # environment settings
        self.state_size = (84, 84, 4)
        self.action_size = action_size

        self.discount_factor = 0.99
        self.no_op_steps = 30

        # optimizer parameters
        self.actor_lr = 2.5e-4
        self.critic_lr = 2.5e-4
        self.threads = 8

        # create model for actor and critic network
        self.actor, self.critic = self.build_model()

        # method for training actor and critic network
        self.optimizer = [self.actor_optimizer(), self.critic_optimizer()]

        self.sess = tf.InteractiveSession()
        K.set_session(self.sess)
        self.sess.run(tf.global_variables_initializer())

        self.summary_placeholders, self.update_ops, self.summary_op = self.setup_summary()
        self.summary_writer = tf.summary.FileWriter('summary/breakout_a3c', self.sess.graph) 
开发者ID:rlcode,项目名称:reinforcement-learning,代码行数:27,代码来源:breakout_a3c.py

示例8: __init__

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def __init__(self, model_param_path='model/model_params.npz', max_batch_size=64):
        """Initalized tensorflow session, set up tensorflow graph, and loads
        pretrained model weights

        Arguments:
            model_params (string) : Path to pretrained model parameters
            max_batch_size (int) : Maximum number of images handled in a single
                                   call to classify.
        """
        self.max_batch_size = max_batch_size
        self.model_param_path = model_param_path

        #Setup tensorflow graph and initizalize variables
        self.session = tf.InteractiveSession()
        self.x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='x')
        self.network, self.predictions, self.probabilities = self._load_model_definition()
        self.session.run( tf.global_variables_initializer() )

        #Load saved parametes
        self._load_model_parameters() 
开发者ID:JoelKronander,项目名称:TensorFlask,代码行数:22,代码来源:mnist_classifiers.py

示例9: create_session

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def create_session(timeout=10000, interactive=True):
  """Create a tf session for the model.
  # This function is slight motification of code written by Alex Mordvintsev

  Args:
    timeout: tfutil param.

  Returns:
    TF session.
  """
  graph = tf.Graph()
  config = tf.ConfigProto()
  config.gpu_options.allow_growth = True
  config.operation_timeout_in_ms = int(timeout*1000)
  if interactive:
    return tf.InteractiveSession(graph=graph, config=config)
  else:
    return tf.Session(graph=graph, config=config) 
开发者ID:tensorflow,项目名称:tcav,代码行数:20,代码来源:utils.py

示例10: make_session

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def make_session(num_cpu=None, make_default=False, graph=None):
    """
    Returns a session that will use <num_cpu> CPU's only

    :param num_cpu: (int) number of CPUs to use for TensorFlow
    :param make_default: (bool) if this should return an InteractiveSession or a normal Session
    :param graph: (TensorFlow Graph) the graph of the session
    :return: (TensorFlow session)
    """
    if num_cpu is None:
        num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count()))
    tf_config = tf.ConfigProto(
        allow_soft_placement=True,
        inter_op_parallelism_threads=num_cpu,
        intra_op_parallelism_threads=num_cpu)
    # Prevent tensorflow from taking all the gpu memory
    tf_config.gpu_options.allow_growth = True
    if make_default:
        return tf.InteractiveSession(config=tf_config, graph=graph)
    else:
        return tf.Session(config=tf_config, graph=graph) 
开发者ID:Stable-Baselines-Team,项目名称:stable-baselines,代码行数:23,代码来源:tf_util.py

示例11: retrieve_seq_length_op2

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def retrieve_seq_length_op2(data):
    """An op to compute the length of a sequence, from input shape of [batch_size, n_step(max)],
    it can be used when the features of padding (on right hand side) are all zeros.

    Parameters
    -----------
    data : tensor
        [batch_size, n_step(max)] with zero padding on right hand side.

    Examples
    --------
    >>> data = [[1,2,0,0,0],
    ...         [1,2,3,0,0],
    ...         [1,2,6,1,0]]
    >>> o = retrieve_seq_length_op2(data)
    >>> sess = tf.InteractiveSession()
    >>> sess.run(tf.initialize_all_variables())
    >>> print(o.eval())
    ... [2 3 4]
    """
    return tf.reduce_sum(tf.cast(tf.greater(data, tf.zeros_like(data)), tf.int32), 1)


# Dynamic RNN 
开发者ID:GuangmingZhu,项目名称:Conv3D_BICLSTM,代码行数:26,代码来源:tensorlayer-layers.py

示例12: run

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def run(self):
        g_emotion = load_graph('emotion.pb')
        x_emotion = g_emotion.get_tensor_by_name('import/Placeholder:0')
        logits_emotion = g_emotion.get_tensor_by_name('import/logits:0')
        sess_emotion = tf.InteractiveSession(graph = g_emotion)

        with open('fast-text-emotion.json') as fopen:
            dict_emotion = json.load(fopen)

        with self.input()['Sentiment'].open('r') as fopen:
            outputs = json.load(fopen)
        for i in range(0, len(outputs), self.batch_size):
            batch_x_text = outputs[i : min(i + self.batch_size, len(outputs))]
            batch_x_text = [t['text'] for t in batch_x_text]
            batch_x_text = [clearstring(t) for t in batch_x_text]
            batch_x = str_idx(batch_x_text, dict_emotion['dictionary'], 100)
            output_emotion = sess_emotion.run(
                logits_emotion, feed_dict = {x_emotion: batch_x}
            )
            labels = [emotion_label[l] for l in np.argmax(output_emotion, 1)]
            for no, label in enumerate(labels):
                outputs[i + no]['emotion_label'] = label

        with self.output().open('w') as fopen:
            fopen.write(json.dumps(outputs)) 
开发者ID:huseinzol05,项目名称:Gather-Deployment,代码行数:27,代码来源:function.py

示例13: visualisation

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def visualisation(final_result):
    # 使用一个新的变量来保存最终输出层向量的结果
    # 因为 embedding 是通过 Tensorflow 中的变量完成的,所以 PROJECTOR 可视化的都是 TF 变量
    y = tf.Variable(final_result, name = TENSOR_NAME)
    summary_writer = tf.summary.FileWriter(LOG_DIR)

    # 通过 PROJECTOR 生成日志
    config = projector.ProjectorConfig()
    embedding = config.embeddings.add()
    embedding.tensor_name = y.name

    # 指定 embedding 对应的原始数据信息
    embedding.metadata_path = META_FILE

    # 指定 sprite 图像及大小
    embedding.sprite.image_path = SPRITE_FILE
    embedding.sprite.single_image_dim.extend([28, 28])

    # 写入日志
    projector.visualize_embeddings(summary_writer, config)

    # 生成会话,写入文件
    sess = tf.InteractiveSession()
    sess.run(tf.global_variables_initializer())
    saver = tf.train.Saver()
    saver.save(sess, os.path.join(LOG_DIR, "model"), TRAINING_STEPS)

    summary_writer.close()


# 主函数先调用模型训练,再处理测试数据,最后将输出矩阵输出到 PROJECTOR 需要的日志文件中 
开发者ID:wdxtub,项目名称:deep-learning-note,代码行数:33,代码来源:mnist_projector_show.py

示例14: use_gpu

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def use_gpu():
    """Configuration for GPU"""
    from keras.backend.tensorflow_backend import set_session
    os.environ['CUDA_VISIBLE_DEVICES'] = str(0)
    config = tf.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.5
    config.gpu_options.allow_growth = True
    set_session(tf.InteractiveSession(config=config)) 
开发者ID:JasonZhang156,项目名称:Sound-Recognition-Tutorial,代码行数:10,代码来源:test.py

示例15: use_gpu

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import InteractiveSession [as 别名]
def use_gpu():
    """Configuration for GPU"""
    from keras.backend.tensorflow_backend import set_session
    os.environ['CUDA_VISIBLE_DEVICES'] = str(0)   # 使用第一台GPU
    config = tf.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.5  # GPU使用率为50%
    config.gpu_options.allow_growth = True    # 允许容量增长
    set_session(tf.InteractiveSession(config=config)) 
开发者ID:JasonZhang156,项目名称:Sound-Recognition-Tutorial,代码行数:10,代码来源:train.py


注:本文中的tensorflow.InteractiveSession方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。