简体   繁体   中英

Tensorflow error: AttributeError: module 'tensorflow' has no attribute 'placeholder'

I'm not very experienced using Tensorflow, and I started using a Google Colab created by Max Woolf ( https://minimaxir.com/2018/05/text-neural.networks/ )

I've edited this post before as I had another simple error I corrected, but then now a bunch of new problems arose with that correction. I'm not experienced as I said, and there's a ton of errors I cannot understand.

I'm trying to train my machine to produce text from a training data file called "marselo", and I suddenly get this error:


AttributeError                            Traceback (most recent call last)
<ipython-input-37-207479944fff> in <module>()
----> 1 textgen = textgenrnn(name='marselo')
      2 
      3 train_function = textgen.train_from_file if train_cfg['line_delimited'] else textgen.train_from_largetext_file
      4 
      5 train_function(

5 frames
/usr/local/lib/python3.6/dist-packages/textgenrnn/textgenrnn.py in __init__(self, weights_path, vocab_path, config_path, name)
     65         self.model = textgenrnn_model(self.num_classes,
     66                                       cfg=self.config,
---> 67                                       weights_path=weights_path)
     68         self.indices_char = dict((self.vocab[c], c) for c in self.vocab)
     69 

/usr/local/lib/python3.6/dist-packages/textgenrnn/model.py in textgenrnn_model(num_classes, cfg, context_size, weights_path, dropout, optimizer)
     16     '''
     17 
---> 18     input = Input(shape=(cfg['max_length'],), name='input')
     19     embedded = Embedding(num_classes, cfg['dim_embeddings'],
     20                          input_length=cfg['max_length'],

/usr/local/lib/python3.6/dist-packages/keras/engine/input_layer.py in Input(shape, batch_shape, name, dtype, sparse, tensor)
    176                              name=name, dtype=dtype,
    177                              sparse=sparse,
--> 178                              input_tensor=tensor)
    179     # Return tensor including _keras_shape and _keras_history.
    180     # Note that in this case train_output and test_output are the same pointer.

/usr/local/lib/python3.6/dist-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

/usr/local/lib/python3.6/dist-packages/keras/engine/input_layer.py in __init__(self, input_shape, batch_size, batch_input_shape, dtype, input_tensor, sparse, name)
     85                                          dtype=dtype,
     86                                          sparse=self.sparse,
---> 87                                          name=self.name)
     88         else:
     89             self.is_placeholder = False

/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py in placeholder(shape, ndim, dtype, sparse, name)
    539         x = tf.sparse_placeholder(dtype, shape=shape, name=name)
    540     else:
--> 541         x = tf.placeholder(dtype, shape=shape, name=name)
    542     x._keras_shape = shape
    543     x._uses_learning_phase = False

AttributeError: module 'tensorflow' has no attribute 'placeholder'

This is the code:

!pip install -q textgenrnn
from google.colab import files
from textgenrnn import textgenrnn
from datetime import datetime
import os


model_cfg = {
    'word_level': False,   # set to True if want to train a word-level model (requires more data and smaller max_length)
    'rnn_size': 128,   # number of LSTM cells of each layer (128/256 recommended)
    'rnn_layers': 3,   # number of LSTM layers (>=2 recommended)
    'rnn_bidirectional': False,   # consider text both forwards and backward, can give a training boost
    'max_length': 30,   # number of tokens to consider before predicting the next (20-40 for characters, 5-10 for words recommended)
    'max_words': 10000,   # maximum number of words to model; the rest will be ignored (word-level model only)
}

train_cfg = {
    'line_delimited': False,   # set to True if each text has its own line in the source file
    'num_epochs': 20,   # set higher to train the model for longer
    'gen_epochs': 5,   # generates sample text from model after given number of epochs
    'train_size': 0.8,   # proportion of input data to train on: setting < 1.0 limits model from learning perfectly
    'dropout': 0.0,   # ignore a random proportion of source tokens each epoch, allowing model to generalize better
    'validation': False,   # If train__size < 1.0, test on holdout dataset; will make overall training slower
    'is_csv': False   # set to True if file is a CSV exported from Excel/BigQuery/pandas
}

file_name = "marselo.txt"
model_name = 'marselo'   # change to set file name of resulting trained models/texts


textgen = textgenrnn(name=model_name)

train_function = textgen.train_from_file if train_cfg['line_delimited'] else textgen.train_from_largetext_file

train_function(
    file_path=file_name,
    new_model=True,
    num_epochs=train_cfg['num_epochs'],
    gen_epochs=train_cfg['gen_epochs'],
    batch_size=1024,
    train_size=train_cfg['train_size'],
    dropout=train_cfg['dropout'],
    validation=train_cfg['validation'],
    is_csv=train_cfg['is_csv'],
    rnn_layers=model_cfg['rnn_layers'],
    rnn_size=model_cfg['rnn_size'],
    rnn_bidirectional=model_cfg['rnn_bidirectional'],
    max_length=model_cfg['max_length'],
    dim_embeddings=100,
    word_level=model_cfg['word_level']) ```

What can I do to resolve this?

I have used the following code and my problem has resolved.

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
textgen = textgenrnn(name=marselo)

This is trying to reference a variable called marselo , which doesn't exist. You probably meant either

textgen = textgenrnn(name='marselo')

or

textgen = textgenrnn(name=model_name)

Can you check the TensorFlow version installed...Tensorflow latest version doesnt support placeholder attribute

https://botbark.com/2019/12/18/attributeerror-module-tensorflow-has-no-attribute-placeholder-tensorflow-2-0/

Try using this:

For Google Colab:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

For VSCode (Works well for Python 3.9.6 and TensorFlow 2.8.0):

import tensorflow._api.v2.compat.v1 as tf
tf.disable_v2_behavior()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM