首页 > 解决方案 > Tensorflow:Module 必须应用在为其实例化的图中

问题描述

虽然问题已经出现在堆栈溢出中,但 Tensorflow: Module 必须应用于它被实例化的图中,但该解决方案不适合我的情况。

我正在尝试使用以下代码

import os  
import sys  
import logging  
from flask import Flask, request, jsonify, send_file  
from flask_cors import CORS  
import pandas as pd  
import numpy as np  
import tensorflow as tf  
import tensorflow_hub as hub  
import numpy as np  
import os 



import pandas as pd  
import re  
import keras.layers as layers  
from keras.models import Model  
from keras import backend as K  
  
import tensorflow as tf  
import tensorflow_hub as hub  
  
  
g = tf.Graph()  
with g.as_default():  
  text_input = tf.placeholder(dtype=tf.string, shape=[None])  
  embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder-large/3")  
  encoding_tensor = embed(text_input)  
  init_op = tf.group([tf.global_variables_initializer(), tf.tables_initializer()])  
g.finalize()  
  
  
def UniversalEmbedding(x):  
    return embed(tf.squeeze(tf.cast(x, tf.string)), signature="default", as_dict=True)["default"]  

def pred(input1, input2):  
    global g, init_op  
    module_url = "https://tfhub.dev/google/universal-sentence-encoder-large/3"  
    embed = hub.Module(module_url)  
    DROPOUT = 0.1  
    # creating a method for embedding and will using method for every input layer  

    # Taking the question1 as input and ceating a embedding for each question before feed it to neural network
    q1 = layers.Input(shape=(1,), dtype=tf.string)  
    embedding_q1 = layers.Lambda(UniversalEmbedding, output_shape=(512,))(q1)  
    # Taking the question2 and doing the same thing mentioned above, using the lambda function  
    q2 = layers.Input(shape=(1,), dtype=tf.string)  
    embedding_q2 = layers.Lambda(UniversalEmbedding, output_shape=(512,))(q2)  

    # Concatenating the both input layer
    merged = layers.concatenate([embedding_q1, embedding_q2])  
    merged = layers.Dense(200, activation='relu')(merged)  
    merged = layers.Dropout(DROPOUT)(merged)  

    # Normalizing the input layer,applying dense and dropout  layer for fully connected model and to avoid overfitting
    merged = layers.BatchNormalization()(merged)  
    merged = layers.Dense(200, activation='relu')(merged)  
    merged = layers.Dropout(DROPOUT)(merged)  

    merged = layers.BatchNormalization()(merged)  
    merged = layers.Dense(200, activation='relu')(merged)  
    merged = layers.Dropout(DROPOUT)(merged)  

    merged = layers.BatchNormalization()(merged)  
    merged = layers.Dense(200, activation='relu')(merged)  
    merged = layers.Dropout(DROPOUT)(merged)  

    # Using the Sigmoid as the activation function and binary crossentropy for binary classifcation as 0 or 1
    merged = layers.BatchNormalization()(merged)  
    pred = layers.Dense(2, activation='sigmoid')(merged)  
    model = Model(inputs=[q1,q2], outputs=pred)  
    # model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])  
    # Loading the save weights
    model.load_weights('/content/drive/MyDrive/Duplicate_Question_Detection/model-04-0.84.hdf5')  


    print("-----------------------")  
    print(input1)  
    print("-----------------------")  
    print(input2)  
    q1 = input1  
    q1 = np.array([[q1],[q1]])  
    q2 = input2  
    q2 = np.array([[q2],[q2]])  

    # Using the same tensorflow session for embedding the test string
    with tf.Session(graph=g) as session:  
      K.set_session(session)  
      session.run(init_op)  
      # Predicting the similarity between the two input questions

        predicts = model.predict([q1, q2], verbose=0)    
        predict_logits = predicts.argmax(axis=1)  
        print("---------------")  
        print(predicts)  
        print("---------------")  
        if(predict_logits[0] == 1):    
          return "Similar"   
        else:   
          return "Not Similar"  
pred("How are you?","How are you?")

我试图确定 input1 和 input2 是否是重复的问题。我有一个用于预测的预训练模型文件。然而,它不断在 pred("你好吗?","你好吗?")

关于这个问题几乎没有答案,而且我发现的任何两个或三个链接都不能解决这个问题。

任何人都可以帮我解决这个问题吗?

链接到代码 - https://github.com/jainanchit51/quora-questions。代码存在于文件 quora_model.py

标签: pythontensorflow

解决方案


推荐阅读