遇到问题在正确导入tensorflow Tokenizer和tensorflow padded_sequences。

huangapple go评论70阅读模式
英文:

Having trouble correctly importing tensorflow Tokenizer and tensorflow padded_sequences

问题

我有一个神经网络,从txt文件中获取数据并使用NLP学习如何像人类一样说话。但每当我加载Tokenizer和padded_sequences时(这两者都是必需的),它们无法正确导入。

我相信我的tensorflow版本或配置可能存在问题,但我已将其更新到最新版本。我可能需要在一个新的虚拟机中测试我的代码以使其正常工作。

这是我的代码:

英文:

I have a neural network that takes data from a txt file and uses nlp to learn how to speak like a human. But whenever I load Tokenizer and padded_sequences, (which are both needed)
they do not correctly import.

I believe that there may be problems with my tensorflow version or configuration but I do have it updated to the latest version. I may need to end up testing my code in a fresh virtual machine to get it working.

Here is my code:

import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import importlib

if importlib.util.find_spec("tensorflow.keras.preprocessing.text.Tokenizer") is not None:
    print("The Tokenizer class has been imported successfully.")
else:
    print("The Tokenizer class has not been imported successfully.")

if importlib.util.find_spec("tensorflow.keras.preprocessing.text.pad_sequences") is not None:
    print("The pad_sequences class has been imported successfully.")
else:
    print("The pad_sequences class has not been imported successfully.")

# Load the text dataset
with open('data.txt', 'r') as f:
    data = f.read()

# Split the data into sentences
sentences = data.split('.')

# Create a tokenizer and fit on the sentences
tokenizer = Tokenizer(filters='')
tokenizer.fit_on_texts(sentences)

# Convert the sentences to sequences of integers
sequences = tokenizer.texts_to_sequences(sentences)

# Create input and target sequences
input_sequences = []
target_sequences = []
for sequence in sequences:
    for i in range(1, len(sequence)):
        input_sequence = sequence[:i]
        target_sequence = sequence[i]
        input_sequences.append(input_sequence)
        target_sequences.append(target_sequence)

# Pad the input sequences
max_sequence_length = max([len(sequence) for sequence in input_sequences])
padded_input_sequences = pad_sequences(input_sequences, maxlen=max_sequence_length)

# Convert the target sequences to one-hot vectors
one_hot_target_sequences = tf.keras.utils.to_categorical(target_sequences, num_classes=len(tokenizer.word_index)+1)

# Create the neural network
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(len(tokenizer.word_index)+1, 100),
    tf.keras.layers.LSTM(128),
    tf.keras.layers.Dense(len(tokenizer.word_index)+1, activation='softmax')
])

# Train the neural network
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(padded_input_sequences, one_hot_target_sequences, epochs=10)

# Generate text
def generate_text(model, tokenizer, max_sequence_length, start_text):
    # Create a sequence of tokens
    tokens = tokenizer.texts_to_sequences([start_text])[0]

    # Generate text until the end of the sentence is reached or max sequence length is reached
    while len(tokens) < max_sequence_length:
        # Pad the input sequence
        padded_sequence = tf.keras.preprocessing.sequence.pad_sequences([tokens], maxlen=max_sequence_length)

        # Get the probability distribution for the next token
        probabilities = model.predict(padded_sequence)[0]

        # Choose the next token with the highest probability
        next_token = np.argmax(probabilities)

        # Add the next token to the sequence
        tokens.append(next_token)

        # Check if the end of the sentence has been reached
        if next_token == tokenizer.word_index['.'] or len(tokens) == max_sequence_length:
            break

    # Convert the tokens back to text
    generated_text = tokenizer.sequences_to_texts([tokens])[0]
    return generated_text

# Generate some text
generated_text = generate_text(model, tokenizer, max_sequence_length, 'Hello, my name is Bard.')
print(generated_text)

Image:
Image from PyCharm underlining the code in red

答案1

得分: 1

以下适用于 TensorFlow 2.12.0。您可以查看链接的 GitHub blobs 上关于 TensorFlow 2.12.0 中 Tokenizer 类和 pad_sequences 函数定义的位置。这些模块的命名以及 TensorFlow/Keras 的结构已经改变了几次,因此正确的导入语句会根据版本而异。

将代码中的:

from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

改为:

from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
英文:

The following worked with TensorFlow 2.12.0. You can see where the Tokenizer class and pad_sequences function are defined on the linked GitHub blobs for TensorFlow 2.12.0. What these modules are called and how TensorFlow/Keras are structured has changed a few times so the correct import statements will be version specific.

Change:

from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

To:

from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences

huangapple
  • 本文由 发表于 2023年4月17日 02:47:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定