求解报错TypeError: slice indices must be integers or None or have an __index__ method

运行环境 pycharm2019.2.3
python 3.7
TensorFlow 2.0

代码如下

import tensorflow as tf
import numpy as np


class DataLoader():
    def __init__(self):
        path = tf.keras.utils.get_file('nietzsche.txt',
                                       origin='https://s3.amazonaws.com/text-datasets/nietzsche.txt')
        with open(path, encoding='utf-8') as f:
            self.raw_text = f.read().lower()
        self.chars = sorted(list(set(self.raw_text)))
        self.char_indices = dict((c, i) for i, c in enumerate(self.chars))
        self.indices_char = dict((i, c) for i, c in enumerate(self.chars))
        self.text = [self.char_indices[c] for c in self.raw_text]

    def get_batch(self, seq_length, batch_size):
        seq = []
        next_char = []
        for i in range(batch_size):
            index = np.random.randint(0, len(self.text) - seq_length)
            seq.append(self.text[index:index + seq_length])
            next_char.append(self.text[index + seq_length])
        return np.array(seq), np.array(next_char)  # [batch_size, seq_length], [num_batch]


class RNN(tf.keras.Model):
    def __init__(self, num_chars, batch_size, seq_length):
        super().__init__()
        self.num_chars = num_chars
        self.seq_length = seq_length
        self.batch_size = batch_size
        self.cell = tf.keras.layers.LSTMCell(units=256)
        self.dense = tf.keras.layers.Dense(units=self.num_chars)

    def call(self, inputs, from_logits=False):
        inputs = tf.one_hot(inputs, depth=self.num_chars)  # [batch_size, seq_length, num_chars]
        state = self.cell.get_initial_state(batch_size=self.batch_size, dtype=tf.float32)
        for t in range(self.seq_length):
            output, state = self.cell(inputs[:, t, :], state)
        logits = self.dense(output)
        if from_logits:
            return logits
        else:
            return tf.nn.softmax(logits)


num_batches = 10
seq_length = 40
batch_size = 50
learning_rate = 1e-3
data_loader = DataLoader()
model = RNN(num_chars=len(data_loader.chars), batch_size=batch_size, seq_length=seq_length)
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
for batch_index in range(num_batches):
    X, y = data_loader.get_batch(seq_length, batch_size)
    with tf.GradientTape() as tape:
        y_pred = model(X)
        loss = tf.keras.losses.sparse_categorical_crossentropy(y_true=y, y_pred=y_pred)
        loss = tf.reduce_mean(loss)
        print("batch %d: loss %f" % (batch_index, loss.numpy()))
    grads = tape.gradient(loss, model.variables)
    optimizer.apply_gradients(grads_and_vars=zip(grads, model.variables))


def predict(self, inputs, temperature=1.):
    batch_size, _ = tf.shape(inputs)
    logits = self(inputs, from_logits=True)
    prob = tf.nn.softmax(logits / temperature).numpy()
    return np.array([np.random.choice(self.num_chars, p=prob[i, :])
                     for i in range(batch_size.numpy())])


X_, _ = data_loader.get_batch(seq_length, 1)

for diversity in [0.2, 0.5, 1.0, 1.2]:
    X = X_
    print("diversity %f:" % diversity)
    for t in range(400):
        y_pred = model.predict(X, diversity)
        print(data_loader.indices_char[y_pred[0]], end='', flush=True)
        X = np.concatenate([X[:, 1:], np.expand_dims(y_pred, axis=1)], axis=-1)
    print("\n")

报错:

Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] on win32
runfile('F:/pyth/pj3/study3.py', wdir='F:/pyth/pj3')
batch 0: loss 4.041161
batch 1: loss 4.026710
batch 2: loss 4.005230
batch 3: loss 3.983728
batch 4: loss 3.920999
batch 5: loss 3.864793
batch 6: loss 3.644211
batch 7: loss 3.375458
batch 8: loss 3.620051
batch 9: loss 3.382381
diversity 0.200000:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\Program Files\JetBrains\PyCharm 2019.2.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "D:\Program Files\JetBrains\PyCharm 2019.2.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "F:/pyth/pj3/study3.py", line 97, in <module>
    y_pred = model.predict(X, diversity)
  File "D:\ProgramData\Anaconda3\envs\kingtf2\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 909, in predict
    use_multiprocessing=use_multiprocessing)
  File "D:\ProgramData\Anaconda3\envs\kingtf2\lib\site-packages\tensorflow_core\python\keras\engine\training_arrays.py", line 722, in predict
    callbacks=callbacks)
  File "D:\ProgramData\Anaconda3\envs\kingtf2\lib\site-packages\tensorflow_core\python\keras\engine\training_arrays.py", line 362, in model_iteration
    batch_ids = index_array[batch_start:batch_end]
TypeError: slice indices must be integers or None or have an __index__ method

可能有问题的地方:

for diversity in [0.2, 0.5, 1.0, 1.2]:
    X = X_
    print("diversity %f:" % diversity)
    for t in range(400):
        y_pred = model.predict(X, diversity)
        print(data_loader.indices_char[y_pred[0]], end='', flush=True)
        X = np.concatenate([X[:, 1:], np.expand_dims(y_pred, axis=1)], axis=-1)
    print("\n")
def predict(self, inputs, temperature=1.):
    batch_size, _ = tf.shape(inputs)
    logits = self(inputs, from_logits=True)
    prob = tf.nn.softmax(logits / temperature).numpy()
    return np.array([np.random.choice(self.num_chars, p=prob[i, :])
                     for i in range(batch_size.numpy())])

1个回答

xhclxh
xhclxh 不是这个问题
3 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问

相似问题

2
vue.js 每次使用router.addRoutes 报错TypeError: routes.forEach is not a function 什么情况
3
Python报错 TypeError: 'int' object has no attribute '__getitem__'
2
求助 Python报错 TypeError: rank() got an unexpected keyword argument 'numeric_only'
3
爬取豆瓣电影存入数据库,报错TypeError: %d format: a number is required, not str
1
python温度转换提示“TypeError: string indices must be integers”
1
scipy解非线性方程组报错TypeError: 'int' object is not callable
2
Python使用类装饰器出现报错:TypeError: test2() missing 1 required positional argument: 'b'
1
python3 sorted()函数报错 TypeError: '<' not supported between instances of 'str' and 'int'
2
django 提交表单后 函数解析参数报错TypeError: not nonetype
2
zepto animate动画报错 已引入fx.js报Uncaught TypeError: this.bind is not a function的错误
1
急求:Json无法从dic-list-dic结构的字典中提取出数据
3
python运行脚本时提示TypeError: float argument required, not str这个错误,有大佬知道原因吗,望解答
1
Django报错TypeError join() argument must be str or bytes, not 'dict'如何解决?
2
python中绘制世界地图TypeError: argument of type 'Key' is not iterable。
1
爬取知乎信息报错--TypeError: string indices must be integers
1
爬取途牛机票信息报错--TypeError: string indices must be integers
1
matplotlib: TypeError: unsupported operand type(s) for -: 'str' and 'float'求解决
2
Python语法错误:TypeError: string indices must be integers
3
如何解决TypeError: expected string or buffer?
2
求解报错TypeError: slice indices must be integers or None or have an __index__ method