我的tensorflow版本为2.3.0,运行上述代码时sess = tf.Session()这句报错module 'tensorflow' has no attribute 'Session',是什么原因?并给出改进后的完整详细代码
时间: 2023-06-14 07:05:51 浏览: 57
这是因为 TensorFlow 2.x 版本已经不再使用 `Session`,而是使用更加简便的 `eager execution`。因此,要在 TensorFlow 2.x 版本中实现上述功能,可以采用以下方式:
```python
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
# 加载数据集
dataset = tfds.load("cornell_movie_dialogs_corpus", split="train[:100]", as_supervised=True)
dataset = dataset.map(lambda x, y: (x, tf.strings.split(y, sep="|").to_tensor(default_value="<PAD>")))
# 构建词表
tokenizer = tfds.features.text.Tokenizer()
vocabulary_set = set()
for text_tensor, _ in dataset:
some_tokens = tokenizer.tokenize(text_tensor.numpy())
vocabulary_set.update(some_tokens)
vocab_size = len(vocabulary_set)
vocab = tf.keras.preprocessing.text.Tokenizer(vocab_size, oov_token="<OOV>")
vocab.fit_on_texts(vocabulary_set)
# 定义模型
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size + 1, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
tf.keras.layers.Dense(64, activation="relu"),
tf.keras.layers.Dense(vocab_size + 1, activation="softmax")
])
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
# 训练模型
BATCH_SIZE = 32
BUFFER_SIZE = 10000
dataset = dataset.shuffle(BUFFER_SIZE).padded_batch(BATCH_SIZE)
model.fit(dataset, epochs=10)
# 测试模型
while True:
user_input = input("You: ")
user_input = tokenizer.tokenize(user_input)
user_input = vocab.texts_to_sequences(user_input)
user_input = tf.keras.preprocessing.sequence.pad_sequences(user_input, maxlen=20, padding="post")
prediction = model.predict(user_input)[0]
predicted_id = np.argmax(prediction)
response = vocab.sequences_to_texts([[predicted_id]])[0]
print("ChitGPT: ", response)
```
这里采用了 `tf.keras.preprocessing.text.Tokenizer` 来构建词表,并将数据集中的文本数据进行了处理,以便于后续模型的训练和测试。模型的定义采用了 `tf.keras.Sequential`,并使用了 `Bidirectional LSTM` 和 `Dense` 层。训练时将数据集进行了打乱和批处理,测试时则接收用户输入并输出模型的回复。