gpt-2 如何为interactive_conditional_samples调用input.txt并写入output.txt

j2qf4p5b  于 6个月前  发布在  其他
关注(0)|答案(8)|浏览(203)

我确实在Windows 10,x64,32 GB RAM,Core i7 2600k和GTX 1050Ti上设置了系统
当我运行这个python src/interactive_conditional_samples.py它要求模型提示>>
然后我输入我的单词,如皮卡丘,输出如下。这个输出显然是不正确的和无关的

======================================== SAMPLE 1 ========================================
-the-cat

You can see more of my artworks on my art page.<|endoftext|>(WOMENSUE.COM) – It's been eight weeks since Republican presidential nominee Donald Trump made news with controversial remarks about U.S. Sen. Kirsten Gillibrand (D-N.Y.) , prompting some to question whether Trump was using a moment of national embarrassment to garner votes.

But the question never has come up among women voters. According to a new poll from Morning Consult among more than 800 likely voters, Clinton trails Trump by 11 points among female voters, 44-36. Even if Clinton wins the women over 30 in the survey – 55-28 in favor of Hillary - the margin is still quite narrow at 3 percentage points.

"If you look at the race and you see women's views, it's clear that most women don't see Trump as a guy who is a threat to their future as women. If you are one of the women and you do see Trump as someone who is a threat to women, then he's not a guy worth getting to know," wrote Morning Consult Associate Director of Public Policy Dan Pate during a recent phone interview.

But some female voters do see Trump in that unflattering light. That's because for most women, Trump is the biggest threat to "the future of women's lives," according to a Morning Consult-NBC News poll conducted Dec. 28 to Dec. 29.

For young women, the question of gender is only slightly less divisive. Fifty-one percent of young women between 18 and 29 in the poll said they view Clinton negatively, compared with 59 percent of young women 42 to 48. But a majority (54 percent) also believe Trump is a threat to men.

But while women vote in droves for their two major party candidates, women are still relatively conservative (44 percent of women between 18 and 29 and 53 percent in the other poll). Just 6 percent of young women believe Trump cares about women, while 36 percent believe he doesn't.

And even among those women who do believe Trump cares about women, his approval rating among female voters is about the same as the ratings among millennial men (60 percent positive to 23 percent negative).

This poll of 1,013 female voters was conducted by telephone Nov. 27-30 with a 3.0 percent margin of error; a general-election poll had a 5.0 percent margin of error and a survey conducted in late November by Fox News had
================================================================================

所以我的第一个问题如下

**1)**我如何将input.txt作为输入,这将有几句话,并将输出写入一个文本文件?

interactive_conditional_samples.py

hparams.json

**3)**如何让它在GPU上而不是CPU上工作?
**4)**我可以让它为给定的句子返回更逻辑的输出吗?

1.我怎么能让它运行在GPU上而不是CPU上?我有GTX 1050 Ti,4 GB RAM
下面是我的CMD的完整输入和输出

C:\gpt-2>python src/interactive_conditional_samples.py
WARNING:tensorflow:From C:\Python37\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:From C:\gpt-2\src\sample.py:46: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
WARNING:tensorflow:From C:\gpt-2\src\sample.py:48: multinomial (from tensorflow.python.ops.random_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.random.categorical instead.
WARNING:tensorflow:From C:\Python37\lib\site-packages\tensorflow\python\training\saver.py:1266: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use standard file APIs to check for files with this prefix.
Model prompt >>> Pikachu
======================================== SAMPLE 1 ========================================
-the-cat

You can see more of my artworks on my art page.<|endoftext|>(WOMENSUE.COM) – It's been eight weeks since Republican presidential nominee Donald Trump made news with controversial remarks about U.S. Sen. Kirsten Gillibrand (D-N.Y.) , prompting some to question whether Trump was using a moment of national embarrassment to garner votes.

But the question never has come up among women voters. According to a new poll from Morning Consult among more than 800 likely voters, Clinton trails Trump by 11 points among female voters, 44-36. Even if Clinton wins the women over 30 in the survey – 55-28 in favor of Hillary - the margin is still quite narrow at 3 percentage points.

"If you look at the race and you see women's views, it's clear that most women don't see Trump as a guy who is a threat to their future as women. If you are one of the women and you do see Trump as someone who is a threat to women, then he's not a guy worth getting to know," wrote Morning Consult Associate Director of Public Policy Dan Pate during a recent phone interview.

But some female voters do see Trump in that unflattering light. That's because for most women, Trump is the biggest threat to "the future of women's lives," according to a Morning Consult-NBC News poll conducted Dec. 28 to Dec. 29.

For young women, the question of gender is only slightly less divisive. Fifty-one percent of young women between 18 and 29 in the poll said they view Clinton negatively, compared with 59 percent of young women 42 to 48. But a majority (54 percent) also believe Trump is a threat to men.

But while women vote in droves for their two major party candidates, women are still relatively conservative (44 percent of women between 18 and 29 and 53 percent in the other poll). Just 6 percent of young women believe Trump cares about women, while 36 percent believe he doesn't.

And even among those women who do believe Trump cares about women, his approval rating among female voters is about the same as the ratings among millennial men (60 percent positive to 23 percent negative).

This poll of 1,013 female voters was conducted by telephone Nov. 27-30 with a 3.0 percent margin of error; a general-election poll had a 5.0 percent margin of error and a survey conducted in late November by Fox News had
================================================================================
lrpiutwd

lrpiutwd1#

顺便说一下,我也测试过句子,输出结果很糟糕
即使在我的电脑上也很慢
酷睿i7 2600K@4.5 GHz,32 GB内存
设置

def interact_model(
    model_name='345M',
    seed=None,
    nsamples=2,
    batch_size=2,
    length=None,
    temperature=1,
    top_k=40,
    models_dir='models',    
):
Model prompt >>> Online Pokemon Game
======================================== SAMPLE 1 ========================================
" as seen on TV with the rest of Pokémon.

Mewtwo can evolve into a Mega Mewtwo from the Pokémon Center after collecting 100 EVs (500 if Mewtwo is caught in the Stadium).

Mewtwo in "Pikachu's Pachislot."

Mewtwo in "Million Shots!"

Mewtwo from "Mii-chan Gets Touched by a Monster."

Mewtwo from "Dewkinesis".

Pikachu's Meowth from "Shopping Cart."

Mewtwo from "Wobbuffet" (Japanese: 南 つけよろ) is an evolutive of Mega Gardevoir.

Mewtwo's design is based on its appearance in the anime Pikachu and the Pokémon Music Squad. Mewtwo, along with Mega Sceptile, and its alternate color scheme Mega Kangaskhan, were featured in a sketch, and Mega Sceptile was later featured in an issue of the same name.[1] In the Japanese dub, Mega Mewtwo is called "Mewtwo Mewtwo" instead and not "Mr. Mewtwo Mewtwo". The artwork for Mega Mewtwo depicts two Pokémon with two Pokémon in their mouths as well as the silhouette of a man in a hoodie holding a large baseball bat.

A promotional artwork of Mewtwo is seen on a card from the Pokémon Card Game series.

Mega Mewtwo does not have the ability to Mega Evolve, unlike other Pokémon with the ability to Mega Evolve. In the Super Smash Bros. series, Mewtwo has the same stat requirements as its Mega version.

Pikachu and other Pokémon in the Super Smash Bros. series have the ability to Mega-Evolve via training.

Wobbuffet, from "Mega-Dewpoint's Story", is the first boss to Mega Evolve.

In the Japanese dub, Mega Mewtwo is called "Dewkinesis."

A promotional artwork of Mewtwo appears in the first issue of Pokemon Diamond and Pearl.

Pikachu is the first to evolve into an alternate art Mewtwo, from the episode "Pokemon Rumble: Battle for Zekrom."

Anime

Mewtwo was one of the Pokémon introduced in Sun & Moon, which was originally featured in Pokémon X and Y. It is featured in the Diamond & Pearl chapter of the Diamond & Pearl series when Brock
======================================== SAMPLE 2 ========================================
" in all of the following formats:

Game Card – Game Card Format

– Game Card Format Special Character Card – Special Character Card Format

– Special Character Card Format Game Card (Awards Style)

– Game Card (Awards Style) Player's Information Box and Promotional Card – In-game Card Format

– In-game Card Format Game Cards

Special Items and Coin Chests have been replaced with a completely new type of Card. Some of them have different names or the same type with the same number of cards as the other cards, but there are no differences in appearance aside from different images and different text.

Each item can be obtained in the following formats:

1st Card: Pokemon

2nd Card: Pokemon

3rd Card: Pokemon with Ability

4th Card: Any Pokemon with Ability

Card

"Player's Information Box" – In-game Card Format

– In-game Card Format Disc 1 - Disc 2 (Japanese version only)

– Disc 1 - Disc 2 (Japanese version only) Disc 3 (Japanese version only)

– Disc 3 (Japanese version only) Disc 4 (Japanese version only)

– Disc 4 (Japanese version only) Disc 5 (Japanese version only)

– Disc 5 (Japanese version only) Player's Information Box and Promotional Card – In-game Card Format

In-game cards

There are several type of cards and in-game cards with the special qualities of each card (for example, there is only one "Energy" type card; that is, it can't be Energy-based). Some of these items are exclusive.

If a card possesses one of the following special qualities, it will be available only after the game ends by entering the "Item Access Code" or by redeeming a prize (but not both: you can obtain multiple prizes in the same playthrough).

The player's information box will usually show something similar to the following, but you can see additional information about the type of card above the box:

Level

The character's level

The nature of the attack it uses

The type of attack it executes

The level the enemy can attack you

Additional data

Certain cards, such as Special Items and Coin Chests, will have stats, movesets, battle abilities, and attacks with additional movesets and/or special attributes or abilities for other cards as well
================================================================================
Model prompt >>> Pikachu is a short, chubby rodent Pokémon. It is covered in yellow fur with two horizontal brown stripes on its back. It has a small mouth, long, pointed ears with black tips, and brown eyes. A each cheek is a red circle that contains a pouch for electricity storage. It has short forearms with five fingers on each paw, and its feet each have three toes. At the base of its lightning bolt-shaped tail is a patch of brown fur. A female will have a V-shaped notch at the end of its tail, which looks like the top of a heart. It is classified as a quadruped, but it has been known to stand and walk on its hind legs.
======================================== SAMPLE 1 ========================================

Ash's Pikachu appeared in Ash and Pikachu after a wild Ash caught it while riding his bicycle.

Major appearances

Pikachu debuted in A PokéRoulette Adventure as one of the Pokémon seen in Ash's Pokémon Pal Joey's Pikachu and the Mystery of Pikachu and the HeartGold and SoulSilver. It reappeared in I Have a Personal Pokémon and its evolutionary line appeared in the opening movie of the Ruby and Sapphire chapter, Pokémon Heroes: Latios and Latias.

Other

An Italian Pikachu was owned by the character Andrea De Nardo. He used it in a prank in the Italian film A Grand Prix For Pikachu.

Two Pikachu models were displayed at The Pokémon Box. One was obtained by Ash on a promotion, and the other Ash's Pikachu in his box of Pokémon in the Kalos region.

A Japanese Pikachu, nicknamed "Neko," sold in the retail department of the Pokémon Trading Card Game in Japan. A Nihon Gion shop in Hoenn, where the same Pikachu model can be played, has the exact silhouette of the previous Japanese Pikachu model.

A Japanese Pikachu model was first seen in a promotional video for Pokémon Center Japan and debuted in a Pikachu and the Clash of X's Wrath special. It appears in Ash's Pokémon Ranger Roost in The Search for the Legendary Pokémon!. In Ash's final battle against Cilan's Pinsir in Let's Choose His Own Adventure!, he defeats it using Pikachu to stop it from using a Stone.

Pokémon

Pikachu A female Japanese Pokémon resembling Pikachu was used by Team Rocket in Ash's first encounter with them. It was later acquired by Ash in his Pokémon Ranger Roost and was later seen in Ash's Pikachu and the Clash of X's Wrath special.

Jirachi A Japanese Pikachu was used by Ash to defeat the Kirlia in Pokémon Ranger Roost. Ash's Nidoqueen stole one from its Trainer. It was later seen being sold in the Kalos region in To Let Go of the Heroes!. It appeared briefly again in Let's Pick a Dream for the Day of the Sun, using it in an Ash's Pikachu.

Rouxels Pikachu Rouxels was one of the Pokémon Ash caught from a Vileplume egg before being attacked by it. A third Rouxels was used by the Johto League Leader when he came up with an idea for one of his Pokémon contests to celebrate Ash's birthday.

Dub
======================================== SAMPLE 2 ========================================

In the anime

In the main series

Major appearances

Cherche, a Yellow Pikachu, first appeared in The First Battle with a Mega-Pikachu. She was caught by Ash and his Pikachu, who later evolved into Mega Gardevoir and Mega Gardevine.

Pikachu was briefly seen being carried around by Pikachu.

The same Cherche appeared in The Last Battle XIII.

Multiple others were shown to exist which were later erased from history by Team Rocket.

A Pikachu appeared throughout Pikachu Adventures.

A male Pikachu's fur was seen in A Battle to the Top!, under the ownership of the Pokéwalker.

A Trainer named Bruno was seen wearing a Pikachu's fur mask in A Battle for Two Americas!. He eventually lost that mask and replaced it with a new one during A Tricky Friendship!, in which he also revealed his identity to Team Rocket.

Minor appearances

Pikachu debuted in Celebi: The Voice of the Forest as one of the Pokémon residing in a forest in Celadon City.

A Trainer's Caterpie appeared in The Final Battle VIII.

A Pikachu appeared in Pika Breeding!, under the ownership of Pidgey.

Professor Oak's Pikachu and his Trainer appeared in The First Battle XIII.

Two Pichu appeared in a fantasy in A Day Break!, under the ownership of the Pokéwalker.

Several Ash's Pikachu made their Pokémon dreams in The Power of Us...!

Three Pikachu were among the Pokémon seen at Professor Oak's Laboratory in A Day in the Life of Arceus.

Several Pachirisu appeared in Volcanion and the Mechanical Marvel. They reappeared in All About Bugsy!.

A Trainer's Pichu appeared in A Challenge in Pokémon!

Pokédex entries

Episode Pokémon Source Entry EP060 Cherche Dawn's Pokédex Cherche, the Yellow Pikachu, is a cute little Pokémon that looks just like a Pichu at first. However, it is actually a type of Pikachu. This concludes the entries from the original series.

Episode Pokémon Source Entry DP077 Cherche Dawn's Pokédex Cherche, the Yellow Pikachu, is a cute-looking Pokémon with a yellow hue. Its fur is black, and there are five clawed feet on its hind legs. Cherche can grow to be an enormous Pokémon. This concludes the entries from the Diamond & Pearl
================================================================================
iyfjxgzm

iyfjxgzm2#

6)当我将长度参数更改为1000时,我得到此错误

模型提示>皮卡丘是一种矮矮胖胖的啮齿动物神奇宝贝。它全身覆盖着黄色的皮毛,背上有两条棕色的横条纹。它有一个小嘴巴,长而尖的耳朵,黑色的尖端,棕色的眼睛。每个脸颊都是一个红色的圆圈,里面有一个储存电力的口袋。它有短前臂,每个爪子上有五个手指,每只脚有三个脚趾。 lightning 状的尾巴底部有一片棕色的皮毛。雌性的尾巴末端有一个V形的缺口,看起来像一个心脏的顶部。它被归类为四足动物,但它可以用后腿站立和行走。
回溯(最近的呼叫最后一个):
文件“C:\Python37\lib\site-packages\tensorflow\python\client\session.py”,第1334行,in _do_call
return fn(*args)
文件“C:\Python37\lib\site-packages\tensorflow\python\client\session.py”,第1319行,in _run_fn
选项、feed_dict、fetch_list、target_list、run_metadata)
文件“C:\Python37\lib\site-packages\tensorflow\python\client\session.py”,第1407行,in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError:indices[0,0] = 1024不在[0,1024)中
{{node sample_sequence/while/model/GatherV2_1}}
在处理上述异常的过程中,又出现了一个异常:
回溯(最近的呼叫最后一个):
文件“src/interactive_conditional_samples.py”,第90行,
fire.Fire(interact_model)
File“C:\Python37\lib\site-packages\fire\core.py”,line 127,in Fire
component_trace = _Fire(component,args,context,name)
文件“C:\Python37\lib\site-packages\fire\core.py”,第366行,在_Fire中
component,remaining_args)
文件“C:\Python37\lib\site-packages\fire\core.py”,第542行,在_CallCallable中
结果= fn(*varargs,**kwargs)
文件“src/interactive_conditional_samples.py”,第80行,interact_model
context:[context_tokens for _ in range(batch_size)]
文件“C:\Python37\lib\site-packages\tensorflow\python\client\session.py”,第929行,运行中
run_metadata_ptr)
文件“C:\Python37\lib\site-packages\tensorflow\python\client\session.py”,第1152行,in _run
feed_dict_tensor,options,run_metadata)
文件“C:\Python37\lib\site-packages\tensorflow\python\client\session.py”,第1328行,in _do_run
run_metadata)
文件“C:\Python37\lib\site-packages\tensorflow\python\client\session.py”,第1348行,in _do_call
raise type(e)(node_def,op,message)
tensorflow.python.framework.errors_impl.InvalidArgumentError:indices[0,0] = 1024不在[0,1024)中
node sample_sequence/while/model/GatherV2_1(定义于C:\gpt-2\src\model.py:157)
由操作“sample_sequence/while/model/GatherV2_1”引起,定义于:
文件“src/interactive_conditional_samples.py”,第90行,
fire.Fire(interact_model)
File“C:\Python37\lib\site-packages\fire\core.py”,line 127,in Fire
component_trace = _Fire(component,args,context,name)
文件“C:\Python37\lib\site-packages\fire\core.py”,第366行,在_Fire中
component,remaining_args)
文件“C:\Python37\lib\site-packages\fire\core.py”,第542行,在_CallCallable中
结果= fn(*varargs,**kwargs)
文件“src/interactive_conditional_samples.py”,第64行,interact_model
temperature=温度,top_k=top_k
文件“C:\gpt-2\src\sample.py”,第73行,在sample_sequence中
back_prop=False,
文件“C:\Python37\lib\site-packages\tensorflow\python\ops\control_flow_ops.py”,第3556行,在while_loop中
return_same_structure)
文件“C:\Python37\lib\site-packages\tensorflow\python\ops\control_flow_ops.py”,第3087行,BuildLoop
pred、body、original_loop_vars、loop_vars、shape_invariants)
文件“C:\Python37\lib\site-packages\tensorflow\python\ops\control_flow_ops.py”,第3022行,in _BuildLoop
body_result = body(*packed_vars_for_body)
文件“C:\Python37\lib\site-packages\tensorflow\python\ops\control_flow_ops.py”,第3525行,
body = lambda i,lv:(i + 1,orig_body(*lv))
文件“C:\gpt-2\src\sample.py”,第45行,正文
next_outputs = step(hparams,prev,past=past)
文件“C:\gpt-2\src\sample.py”,第33行,步骤
lm_output = model.model(hparams=hparams,X=tokens,past=past,reuse=tf. token_REUSE)
模型中的文件“C:\gpt-2\src\model.py”,第157行
h = tf.gather(wte,X)+ tf.gather(wpe,positions_for(X,past_length))
文件“C:\Python37\lib\site-packages\tensorflow\python\util\dispatch.py”,第180行,在 Package 器中
return target(*args,**kwargs)
文件“C:\Python37\lib\site-packages\tensorflow\python\ops\array_ops.py”,第3273行,在gather中
return gen_array_ops. axis_v2(params,indices,axis,name=name)
文件“C:\Python37\lib\site-packages\tensorflow\python\ops\gen_array_ops.py”,第4390行,在python v2中
“GatherV2”,params=params,indices=indices,axis=axis,name=name)
文件“C:\Python37\lib\site-packages\tensorflow\python\framework\op_def_library.py”,第788行,in _apply_op_helper
op_def=op_def)
File“C:\Python37\lib\site-packages\tensorflow\python\util\deprecation.py”,line 507,in new_func
return func(*args,**kwargs)
文件“C:\Python37\lib\site-packages\tensorflow\python\framework\ops.py”,第3300行,在create_op中

op_def=op_def)
文件“C:\Python37\lib\site-packages\tensorflow\python\framework\ops.py”,第1801行,在init
self._traceback = tf_stack.extract_stack()
InvalidArgumentError(参见上面的追溯):indices[0,0] = 1024不在[0,1024]中
node sample_sequence/while/model/GatherV2_1(定义于C:\gpt-2\src\model.py:157)

o75abkj4

o75abkj43#

同样的问题(6),如果你有解决方案,现在,请告诉我,谢谢:)

cuxqih21

cuxqih214#

1.你需要玩一点python。文件阅读(使用控制字符串拆分,JSON或其他方法)或解析目录中的多个文件。我的首选方式是带web界面的数据库,然而,我不运行自动化。
1.我想不是,但如果你编程自己的功能,那么你可以有更多。再次,我的参数是由数据库控制的。

  1. Nvidia仅(好吧,它可以在AMD上工作,但afaik Linux只和挠头很多)。117 M将工作在2GB的GPU,345 M我猜4GB的GPU。我运行我的Nvidia Gefore 1660 6GB,我可以确认,它可以运行多达7个样本在一批,但可以崩溃。6个样本是确定的,但崩溃时,循环。5个样本是安全的。
    1.我猜保持完全相同的语法和风格的数据上学到了?然而,正如在开发人员自述,很多还没有理解的人工智能行为(因此研究).
    1.安装GPU版本的tensorflow。它是在自述文件中编写的。要获得正确的cudnn和cuda版本,请参考谷歌搜索您愿意安装的tensorflow版本。还有一个指南,将告诉您如何确切地更新PATH变量(在Windows的情况下)。
    这是CPU上的速度慢,是的.它需要87秒从单词中生成一批5个样本“突然”,使用最大输出长度可能,在Gefore 1660 6GB:
39. Waiting for DB data
T: 1.0 | K: 0.0 | P: 0.1, 0.9 | P_M: 0.0, 0.5 | P_S: 0 | S: 5 | B: 5 | ID: s08k6ih5s5oqjlcc55tcandlg0 |>>> Suddenly
>> Response Saved as: D:\!OpenAI_stories\OpenAI-20190704220718.txt
 !! Time taken (sec): 87.18098640441895
length = hparams.n_ctx - context_length

是每个样本可能的最大长度,因此使用一个令牌,它可以输出多达1023个afaik。如果您想获得1000,则不能使用超过24个令牌作为输入

z9smfwbn

z9smfwbn5#

@FurkanGozukara我已经为此创建了PR。你可以看看#174

13z8s7eq

13z8s7eq6#

1050ti?忘了GPU吧。你需要2080ti

luaexgnf

luaexgnf7#

嘿,我如何使GPT-2创建其输出到一个指定的文本文件?

i2loujxw

i2loujxw8#

下面是我用来连接GPT-2模型的脚本。我让它将文本输出到我的语音合成模块,但是你可以很容易地使用“with file as.”并将变量(下面脚本中的“text”-向下滚动到靠近末尾的while True块)内容写入文件.

#!/usr/bin/env python3

import fire
import json
import os
import numpy as np
import tensorflow as tf
import zmq
import time
context = zmq.Context()

print("Connecting to Speech Center")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")   #5556 is visual, 5558 is language, 555$

import model, sample, encoder

def interact_model(
    model_name='345M', #345M on Pi4B4 or 8 only (memory allocation issue) 774 & 1558 too big for Pi4b8G too.
    seed=None,
    nsamples=1,
    batch_size=1,
    length=140,
    temperature=1.2,
    top_k=48,
    top_p=0.7,
    models_dir='models',
):

    models_dir = os.path.expanduser(os.path.expandvars(models_dir))
    if batch_size is None:
        batch_size = 1
    assert nsamples % batch_size == 0

    enc = encoder.get_encoder(model_name, models_dir)
    hparams = model.default_hparams()
    with open(os.path.join(models_dir, model_name, 'hparams.json')) as f:
        hparams.override_from_dict(json.load(f))

    if length is None:
        length = hparams.n_ctx // 2
    elif length > hparams.n_ctx:
        raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx)

    with tf.Session(graph=tf.Graph()) as sess:
        context = tf.placeholder(tf.int32, [batch_size, None])
        np.random.seed(seed)
        tf.set_random_seed(seed)
        output = sample.sample_sequence(
            hparams=hparams, length=length,
            context=context,
            batch_size=batch_size,
            temperature=temperature, top_k=top_k, top_p=top_p
        )

        saver = tf.train.Saver()
        ckpt = tf.train.latest_checkpoint(os.path.join(models_dir, model_name))
        saver.restore(sess, ckpt)

        while True:
            raw_text = input("\n\nModel prompt >>> ")
            while not raw_text:
                print('Prompt should not be empty!')
                raw_text = input("\n\nModel prompt >>> ")
            context_tokens = enc.encode(raw_text)
            generated = 0
            for _ in range(nsamples // batch_size):
                out = sess.run(output, feed_dict={
                    context: [context_tokens for _ in range(batch_size)]
                })[:, len(context_tokens):]
                for i in range(batch_size):
                    generated += 1
                    text = enc.decode(out[i])
                    stripFrag = text.rsplit(".", 1)
                    text = stripFrag[0] + "."  #Truncates after last "." to strip sent. frags.
                    print("=" * 40 + " SAMPLE " + str(generated) + " " + "=" * 40)
                    print(text)
                    socket.send_string(text)
                    message = socket.recv()
                    message = message.decode('utf-8')
                    if message==text:
                        print("1")
                    else:
                        print("0")
            print("=" * 80)

if __name__ == '__main__':
    fire.Fire(interact_model)

相关问题