阅读tensorflow documentation进行文本分类时,我在下面建立了一个脚本,用于训练文本分类模型(正/负)。有一件事我不确定。如何保存模型以便以后重用?另外,如何测试我拥有的输入测试集?在import tensorflow as tf

import tensorflow_hub as hub

import matplotlib.pyplot as plt

import numpy as np

import os

import pandas as pd

import re

import seaborn as sns

# Load all files from a directory in a DataFrame.

def load_directory_data(directory):

data = {}

data["sentence"] = []

data["sentiment"] = []

for file_path in os.listdir(directory):

with tf.gfile.GFile(os.path.join(directory, file_path), "r") as f:

data["sentence"].append(f.read())

data["sentiment"].append(re.match("\d+_(\d+)\.txt", file_path).group(1))

return pd.DataFrame.from_dict(data)

# Merge positive and negative examples, add a polarity column and shuffle.

def load_dataset(directory):

pos_df = load_directory_data(os.path.join(directory, "pos"))

neg_df = load_directory_data(os.path.join(directory, "neg"))

pos_df["polarity"] = 1

neg_df["polarity"] = 0

return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)

# Download and process the dataset files.

def download_and_load_datasets(force_download=False):

dataset = tf.keras.utils.get_file(

fname="aclImdb.tar.gz",

origin="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz",

extract=True)

train_df = load_dataset(os.path.join(os.path.dirname(dataset),

"aclImdb", "train"))

test_df = load_dataset(os.path.join(os.path.dirname(dataset),

"aclImdb", "test"))

return train_df, test_df

# Reduce logging output.

tf.logging.set_verbosity(tf.logging.ERROR)

train_df, test_df = download_and_load_datasets()

train_df.head()

# Training input on the whole training set with no limit on training epochs.

train_input_fn = tf.estimator.inputs.pandas_input_fn(

train_df, train_df["polarity"], num_epochs=None, shuffle=True)

# Prediction on the whole training set.

predict_train_input_fn = tf.estimator.inputs.pandas_input_fn(

train_df, train_df["polarity"], shuffle=False)

# Prediction on the test set.

predict_test_input_fn = tf.estimator.inputs.pandas_input_fn(

test_df, test_df["polarity"], shuffle=False)

embedded_text_feature_column = hub.text_embedding_column(

key="sentence",

module_spec="https://tfhub.dev/google/nnlm-en-dim128/1")

estimator = tf.estimator.DNNClassifier(

hidden_units=[500, 100],

feature_columns=[embedded_text_feature_column],

n_classes=2,

optimizer=tf.train.AdagradOptimizer(learning_rate=0.003))

# Training for 1,000 steps means 128,000 training examples with the default

# batch size. This is roughly equivalent to 5 epochs since the training dataset

# contains 25,000 examples.

estimator.train(input_fn=train_input_fn, steps=1000);

train_eval_result = estimator.evaluate(input_fn=predict_train_input_fn)

test_eval_result = estimator.evaluate(input_fn=predict_test_input_fn)

print "Training set accuracy: {accuracy}".format(**train_eval_result)

print "Test set accuracy: {accuracy}".format(**test_eval_result)

目前,如果我运行上面的脚本,它会重新训练完整的模型。我想重用这个模型,并将其输出为我所拥有的一些示例文本。我怎么能这么做?在

我尝试了以下方法来保存:

^{pr2}$

但这会抛出一个错误,即Value Error: No variables to save

python tensorflow 文本提取_如何在tensorflow中保存文本分类模型?相关推荐

  1. python字符串标签转化_如何在TensorFlow中将字符串标签转换为一个热向量?

    我是TensorFlow的新手,想读一个逗号分隔值(csv)文件,它包含两列,第1列是索引,第2列是标签字符串.我有以下代码,它逐行读取csv文件中的行,并且我能够使用print语句正确地获取csv文 ...

  2. python怎么字体加阴影_如何在pythonptx中给文本添加阴影?

    我正在做一个项目,我必须用pythonptx创建一个PowerPoint.我需要添加有阴影的文本,使其显示如下: 如何在pythonptx中使用阴影格式化文本?在 下面是我使用的代码:from ppt ...

  3. python的loc函数_如何在pandas中使用loc、iloc函数进行数据索引(入门篇)

    在数据分析过程中,很多时候我们需要从数据表中提取出我们需要的部分,而这么做的前提是我们需要先索引出这一部分数据.今天我们就来探索一下,如何在pandas中使用loc函数和iloc函数索引数据. 今天我 ...

  4. android 文本后图标_如何在Android中更改文本,图标等的大小

    android 文本后图标 Let's face it: no matter how good the screens are on our phones and tablets, the text ...

  5. txt文本变为粗体_如何在PHP中使文本变为粗体?

    txt文本变为粗体 Sometimes we might want to display text with style. That it's font, color, make it bold, i ...

  6. python绘图背景透明_如何在 Matplotlib 中更改绘图背景

    介绍Matplotlib是Python中使用最广泛的数据可视化库之一.无论是简单还是复杂的可视化项目,它都是大多数人的首选库.在本教程中,我们将研究如何在Matplotlib中更改绘图的背景.导入数据 ...

  7. python 追加写文件_如何往文件中追加文本

    在用python从网站中爬取内容并保存到本地的txt文件中时,发现每次写入都是把txt文件中原来存在的内容覆盖掉了,那么如何才能在原来的基础上继续往里面添加内容呢? 1.原来的打开文件的方式是:fil ...

  8. python 运行r语言_如何在R中运行Python

    python 运行r语言 尽管我很喜欢R,但很显然Python还是一种很棒的语言-既适用于数据科学又适用于通用计算. R用户想要在Python中做一些事情可能有充分的理由. 也许这是一个很棒的库,还没 ...

  9. python捕获所有异常状态_如何在scrapy中捕获并处理各种异常

    前言 使用scrapy进行大型爬取任务的时候(爬取耗时以天为单位),无论主机网速多好,爬完之后总会发现scrapy日志中"item_scraped_count"不等于预先的种子数量 ...

最新文章

  1. 大数据面试题及答案 100道 (2021最新版)
  2. 四种软件架构演进史,会一种就很牛逼了!
  3. 讨厌php机试_[转载]PHP上机面试题
  4. 独家 | 使EfficientNet更有效率的三种方法(附链接)
  5. Codeforces Round #260 (Div. 1) A - Boredom DP
  6. qsort()编译器自带快速排序的用法
  7. 使用LitJson进行序列化和反序列化
  8. CCCF译文 | 从计算思维到计算行动*
  9. Linux新加硬盘添加一个新的LVM磁盘组
  10. android 相机应用程序,2020年最佳Android相机的应用程序
  11. 如何利用Webp和http缓存节省30%的网络流量
  12. 大牛写的Openstack虚拟机创建细节
  13. 17. --cover-- 覆盖掩盖 (词19)
  14. Fork/Join 框架-设计与实现(翻译自论文《A Java Fork/Join Framework》原作者 Doug Lea)...
  15. ffmpeg下载视频
  16. php网站 视频马赛克,如何给视频加马赛克 菜鸟也能学会的视频加马赛克解决方案...
  17. 408计算机考研交流群,考研初试复习经验分享(计算机408)
  18. VS 2015社区版离线下载
  19. 面试官的窒息逼问: 到底什么是面向接口编程?
  20. python调用百度云文字识别

热门文章

  1. oracle切换sqlserver,ORACLE语法转换成sqlserver,该如何解决
  2. servlet-cookie实现向客户端写cookie信息
  3. android适配性报告,关于Android的多种屏幕适配
  4. centos6.5安装apache php,Centos66安装apache24
  5. php yii框架连接数据库,【PHP开发框架】yii框架怎样衔接数据库
  6. 内核aio_linux内核aio功能
  7. c语言指针易错情况,C语言/C++从入门到精通之指针易错点总结
  8. html css 表头,css固定表格表头(各浏览器通用)
  9. vue根据条件显示字段
  10. PHP案例:实现数据库增删改查功能