Tuple object cannot be interpreted as an integer python

При начале обучения нейронной сети выходит ошибка: ‘tuple’ object cannot be interpreted as an integer

Я запускаю нейронную сеть на keras, он вроде бы адекватно занружает изображения, но потом вылезает эта ошибка:

`Traceback (most recent call last): File "D:\Documents\Desktop\Python\ClassificationTraining\ClassificationTraining\ClassificationTraining.py", line 78, in validation_steps= nb_val_samples // batch_size File "C:\Program Files\Python36\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\keras\engine\training.py", line 1418, in fit_generator initial_epoch=initial_epoch) File "C:\Program Files\Python36\lib\site-packages\keras\engine\training_generator.py", line 181, in fit_generator generator_output = next(output_generator) File "C:\Program Files\Python36\lib\site-packages\keras\utils\data_utils.py", line 601, in get six.reraise(*sys.exc_info()) File "C:\Program Files\Python36\lib\site-packages\six.py", line 693, in reraise raise value File "C:\Program Files\Python36\lib\site-packages\keras\utils\data_utils.py", line 595, in get inputs = self.queue.get(block=True).get() File "C:\Program Files\Python36\lib\multiprocessing\pool.py", line 608, in get raise self._value File "C:\Program Files\Python36\lib\multiprocessing\pool.py", line 119, in worker result = (True, func(*args, **kwds)) File "C:\Program Files\Python36\lib\site-packages\keras\utils\data_utils.py", line 401, in get_index return _SHARED_SEQUENCES[uid][i] File "C:\Program Files\Python36\lib\site-packages\keras_preprocessing\image.py", line 1441, in __getitem__ return self._get_batches_of_transformed_samples(index_array) File "C:\Program Files\Python36\lib\site-packages\keras_preprocessing\image.py", line 1916, in _get_batches_of_transformed_samples dtype=self.dtype) TypeError: 'tuple' object cannot be interpreted as an integer` 
import numpy as np from keras.models import Sequential from keras.layers import Activation, Dense, Flatten, Dropout from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.utils import np_utils from keras.optimizers import SGD from keras.preprocessing.image import ImageDataGenerator np.random.seed(42) datagen = ImageDataGenerator(rescale = 1. / 255) train_dir = r"D:\Documents\Desktop\data\train" val_dir = r"D:\Documents\Desktop\data\val" test_dir = r"D:\Documents\Desktop\data\test" images_height = 256, images_width = 256, train_generator = datagen.flow_from_directory( train_dir, target_size=(images_height, images_width), batch_size=5, class_mode='binary' ) val_generator = datagen.flow_from_directory( val_dir, target_size=(images_height, images_width), batch_size=3, class_mode='binary' ) test_generator = datagen.flow_from_directory( test_dir, target_size=(images_height, images_width), batch_size=3, class_mode='binary' ) model = Sequential() model.add(Conv2D(15, (3, 3), input_shape = (256, 256, 3))) model.add(Activation('relu')) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(15, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(30, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D()) model.add(Flatten()) model.add(Dense(30)) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile( optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'], ) batch_size = 3 nb_train_samples = 68 nb_val_samples = 11 nb_test_samples = 13 model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=100, validation_data=val_generator, validation_steps= nb_val_samples // batch_size ) scores = model.evaluate_generator(test_generator, nb_test_samples // batch_size) print("Аккуратность на тестовых данных: %.2f%%" % (scores[1]*100)) 

Я так понимаю, что он считает целое число за кортеж, но почему? В интернете предлагают закрыть двойными скобками, по типу ((64, 64)), но это не помогло. Ставил цифру вручную, но результат такой же. Ещё я удалил 77-ю строку, и ошибка перескочила на 76-ю. Я добавил [0] в конец, если вдруг он действительно выдаёт кортеж, но появилась такая ошибка:

'Traceback (most recent call last): File "D:\Documents\Desktop\Python\ClassificationTraining\ClassificationTraining\ClassificationTraining.py", line 79, in validation_steps= val_steps[0], TypeError: 'int' object is not subscriptable' 

То есть, программа всё-таки понимает, что это число. Но что ей мешает? В общем, я не понимаю, что ей не нравится. Помогите пожалуйста, заранее спасибо.

Читайте также:  Html размер шрифта от разрешения

Источник

‘Tuple’ object cannot be interpreted as an integer error

Welcome to Stack Overflow! Please include the full stack trace of your error in your question. Please also take the tour, read what’s on-topic here, How to Ask, and the question checklist. Helpful links:How to debug small programs. | What is a debugger and how can it help me diagnose problems?

2 Answers 2

When used the way you’re trying to use it, the range() function wants two arguments: start and stop , not a single tuple with the two values. There are many ways to give it two values:

def range_check(obj1, obj2): range_start, range_stop = obj2 return obj1 in range(range_start, range_stop) 
def range_check(obj1, obj2): return obj1 in range(obj2[0], obj2[1]) 
def range_check(obj1, obj2): return obj1 in range(*obj2) 
if a == b: return True else return False 

because a == b is already True or False .

The issue you have is that the tuple needs to be unpacked. You can do this with the * operator like so:

import sys obj1 = int(sys.argv[1]) obj2 = (1900, 2100) def range_check(integer_value, valid_range): return integer_value in range(*valid_range) print(range_check(obj1, obj2)) 

As noted in another answer, you can omit the broken-out if statement. Also, it is best practice to use arguments that are not variables in the outer scope. This way you don’t have any strange behavior with collisions shadowing one another unexpectedly.

Источник

How To Resolve TypeError: Tuple Object Cannot Be Interpreted As An Integer In Python

TypeError: tuple object cannot be interpreted as an integer

Have you ever encountered the TypeError: tuple object cannot be interpreted as an integer error in Python? Does this fix make you curious? Read the article below to know why it happens and how to fix it.

What causes the TypeError: tuple object cannot be interpreted as an integer?

The TypeError: tuple object cannot be interpreted as an integer happens because a function where you pass a tuple to a function and mistake that function parameter as an integer.

myTuple = ( 1, 2, 3, 4, 5 ) for i in range(myTuple): print(i)
Traceback (most recent call last): File "./prog.py", line 3, in for i in range(myTuple): TypeError: 'tuple' object cannot be interpreted as an integer

How to solve this error?

The function parameter must be an integer

In the above example, the error message occurs on line 3. The reason is because we are trying to create a range using a tuple, but the range() can only generate integer ranges between integer values. To fix this, let’s use the len() function to find the tuple length.

  • str: a string of characters string, bytes, tuple, list, range, dictionary, set, or frozen set for which you want to calculate the length.

The len() function returns the number of characters in the input string.

Note: Do not pass the parameter, or the program will report a TypeError error if the parameter is invalid.

  • Create a tuple.
  • Use the len() function to find the tuple length so that the range() function can generate a range of parameters that are the tuple length so there will be no error.
myTuple = ( 1, 2, 3, 4, 5 ) for i in range(len(myTuple)): print(i)

Tuple access

Tuple access is similar to list index access. The elements in a tuple are numbered from 0 to the end in the left-to-right direction or from -1 to the end in the right-to-left direction.

myTuple = ( 1, 2, 3, 4, 5 ) # Performs access to elements in a tuple print('The first element:', myTuple[0]) print('The second element:', myTuple[1])
The first element: 1 The second element: 2

If you want to get an array of elements in a tuple, you can use the following expression:

  • start: a position to start getting the element. Please leave it blank. The default is to get it from the beginning.
  • end: the end position to get the element. Could you leave it blank by default?
  • Create tuple.
  • Implement substring. I took the example of leaving ‘start’ and ‘end’ blank so you can imagine.
myTuple = ( 1, 2, 3, 4, 5 ) # Performs access to elements in a tuple print('Substring in tuple leave start blank:', myTuple[:4]) print('Substring in tuple leave end blank:', myTuple[0:])
Substring in tuple leave start blank: (1, 2, 3, 4) Substring in tuple leave end blank: (1, 2, 3, 4, 5)

Summary

The TypeError: tuple object cannot be interpreted as an integer is not too hard to fix. Method 1 is very easy. Hopefully, through my article, you will have your solution. If there is another way, let us know in the comments below. Thank you for reading!

Maybe you are interested:

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Источник

model.fit_generator : ‘tuple’ object cannot be interpreted as an integer

I was doing dog vs cat classification using deep learning. When I am fitting the model using fit generator , the following error is coming.:

'tuple' object cannot be interpreted as an integer 

I don’t know where I am doing wrong! My full code is below. I was following the tutorial from https://data-flair.training/blogs/cats-dogs-classification-deep-learning-project-beginners/ the code is also same. but I am getting the error!

import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from keras.models import Sequential from keras.layers import Conv2D,MaxPooling2D,Dropout,Flatten,Dense,Activation,BatchNormalization model=Sequential() model.add(keras.Input(shape=(128,128,3))) model.add(layers.Conv2D(32, 3, activation="relu")) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(layers.Conv2D(64,3,activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(layers.Conv2D(128,3,activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512,activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(2,activation='sigmoid')) model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy']) train_df, validate_df = train_test_split(df, test_size = 0.2, random_state = 42) train_df = train_df.reset_index(drop=True) validate_df = validate_df.reset_index(drop=True) from keras.callbacks import EarlyStopping,ReduceLROnPlateau earlystop=EarlyStopping(patience=10) learning_rate_reduction=ReduceLROnPlateau(monitor='val_acc',patience=2,verbose=1,factor=0.5,min_lr=0.00001) callbacks=[earlystop,learning_rate_reduction] train_datagen = ImageDataGenerator(rotation_range=15, rescale=1./255, shear_range=0.1, zoom_range=0.2, horizontal_flip=True, width_shift_range=0.1, height_shift_range=0.1 ) train_generator = train_datagen.flow_from_dataframe(train_df, "/content/drive/MyDrive/Cat_Dog/dogs-vs-cats/train/train/",x_col='filename',y_col='category', target_size=Image_Size, class_mode='categorical', batch_size=batch_size) validation_datagen = ImageDataGenerator(rescale=1./255) validation_generator = validation_datagen.flow_from_dataframe( validate_df, "/content/drive/MyDrive/Cat_Dog/dogs-vs-cats/train/train/", x_col='filename', y_col='category', target_size=Image_Size, class_mode='categorical', batch_size=batch_size ) test_datagen = ImageDataGenerator(rotation_range=15, rescale=1./255, shear_range=0.1, zoom_range=0.2, horizontal_flip=True, width_shift_range=0.1, height_shift_range=0.1) test_generator = train_datagen.flow_from_dataframe(train_df, "/content/drive/MyDrive/Cat_Dog/dogs-vs-cats/test1",x_col='filename',y_col='category', target_size=Image_Size, class_mode='categorical', batch_size=batch_size) df["category"] = df["category"].replace() train_df,validate_df = train_test_split(df,test_size=0.20, random_state=42) train_df = train_df.reset_index(drop=True) validate_df = validate_df.reset_index(drop=True) total_train=train_df.shape[0] total_validate=validate_df.shape[0] batch_size=15 epochs=10 history = model.fit_generator( train_generator, epochs=epochs, validation_data=validation_generator, validation_steps=total_validate//batch_size, steps_per_epoch=total_train//batch_size, callbacks=callbacks ) 

Источник

Оцените статью