作家
登录

利用 TensorFlow 实现上下文的 Chat-bots

作者: 来源: 2017-06-28 15:02:14 阅读 我要评论

请留意,我们的数据次序已经被打乱了。 TensorFlow 会拔取个中的一些数据作为测试数据,用来测试练习的模型的精确度。

如不雅我们不雅察单个的 x 向量和 y 向量,那么这就是一个词袋模型,一个表示须要匹配的模式,一个表示匹配的目标。

train_x example: [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1] train_y example: [0, 0, 1, 0, 0, 0, 0, 0, 0]

接下来,我们来构建我们的模型。

# reset underlying graph datatf.reset_default_graph()# Build neural networknet = tflearn.input_data(shape=[None, len(train_x[0])])net = tflearn.fully_connected(net, 8)net = tflearn.fully_connected(net, 8)net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')net = tflearn.regression(net)# Define model and setup tensorboardmodel = tflearn.DNN(net, tensorboard_dir='tflearn_logs')# Start training (apply gradient descent algorithm)model.fit(train_x, train_y, n_epoch=1000, batch_size=8, show_metric=True)model.save('model.tflearn')

这个模型应用的是 2 层神经收集模型,跟这篇文┞仿中的是一样的。

interactive build of a model in tflearn

我们完成了这部分的工作,如今须要保存我们的模型和文档, 以便在后续的代码中可以应用它们。

# save all of our data structuresimport picklepickle.dump( {'words':words, 'classes':classes, 'train_x':train_x, 'train_y':train_y}, open( "training_data", "wb" ) )

构建我们的聊天机械人框架

我们将构建一个简单的状况机来处理响应,并且应用我们的在上一部分中提到的意图模型来作为我们的分类器。如不雅你想懂得聊天机械人的工作道理,那么可以点击这里。

我们须要导入和上一部分雷同的包,然后 un-pickle 我们的模型和句子,正如我们在上一部分中操作的。请记住,我们的聊天机械人框架与我们的模型是分开构建的 —— 除非意图模式改变了,那么我们须要从新运行我们的模型,不然不须要重构模型。如不雅拥稀有百种意图和数千种模式,模许可能须要几分钟的时光才能构建完成。

classify('is your shop open today?')[('opentoday', 0.9264171123504639)]
# restore all of our data structuresimport pickledata = http://ai.51cto.com/art/201706/pickle.load( open( "training_data", "rb" ) )words = data['words']classes = data['classes']train_x = data['train_x']train_y = data['train_y']# import our chat-bot intents fileimport jsonwith open('intents.json') as json_data:    intents = json.load(json_data)
# load our saved modelmodel.load('./model.tflearn')

在我们开端处理对话意图之前,我们须要一种大年夜用户输入数据生词词袋的办法。而这个办法,跟我们前面所应用的办法是雷同的。

def clean_up_sentence(sentence):    # tokenize the pattern    sentence_words = nltk.word_tokenize(sentence)    # stem each word    sentence_words = [stemmer.stem(word.lower()) for word in sentence_words]    return sentence_words# return bag of words array: 0 or 1 for each word in the bag that exists in the sentencedef bow(sentence, words, show_details=False):    # tokenize the pattern    sentence_words = clean_up_sentence(sentence)    # bag of words    bag = [0]*len(words)      for s in sentence_words:        for i,w in enumerate(words):            if w == s:                 bag[i] = 1                if show_details:                    print ("found in bag: %s" % w)    return(np.array(bag))
p = bow("is your shop open today?", words)print (p)[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0]

如今,我们可以开端构建我们的响应处理器了。

ERROR_THRESHOLD = 0.25def classify(sentence):    # generate probabilities from the model    results = model.predict([bow(sentence, words)])[0]    # filter out predictions below a threshold    results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD]    # sort by strength of probability    results.sort(key=lambda x: x[1], reverse=True)    return_list = []    for r in results:        return_list.append((classes[r[0]], r[1]))    # return tuple of intent and probability    return return_listdef response(sentence, userID='123', show_details=False):    results = classify(sentence)    # if we have a classification then find the matching intent tag    if results:        # loop as long as there are matches to process        while results:            for i in intents['intents']:                # find a tag matching the first result                if i['tag'] == results[0][0]:                    # a random response from the intent                    return print(random.choice(i['responses']))            results.pop(0)	
				
			

  推荐阅读

  美CIA CherryBlossom项目暴露路由器安全问题

维基解密最新宣布的CIA黑客对象中包含了CherryBlossom项目,该项目凸显了路由器的安然问题,包含缺乏固件签名方面的验证等。“在企业级产品方面,大年夜型路由器制造商已经供给签名固>>>详细阅读


本文标题:利用 TensorFlow 实现上下文的 Chat-bots

地址:http://www.17bianji.com/lsqh/35941.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)