如何解决 TypeError:'int' 和 'str' 的实例之间不支持'<'?
Posted
技术标签:
【中文标题】如何解决 TypeError:\'int\' 和 \'str\' 的实例之间不支持\'<\'?【英文标题】:How do I resolve TypeError: '<' not supported between instances of 'int' and 'str'?如何解决 TypeError:'int' 和 'str' 的实例之间不支持'<'? 【发布时间】:2020-04-07 20:07:24 【问题描述】:我正在尝试使用以下代码从以下链接训练 Keras-I3D 模型:
https://github.com/srijandas07/i3d。我稍微修改了代码,但我可以让它工作。
导入的模块是
import os
os.environ['KERAS_BACKEND'] = 'tensorflow'
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="3"
from keras.layers import Dense, Flatten, Dropout, Reshape
from keras import regularizers
from keras.preprocessing import image
from keras.models import Model, load_model
from keras.applications.vgg16 import preprocess_input
from keras.utils import to_categorical
from keras.optimizers import SGD
from i3d_inception import Inception_Inflated3d, conv3d_bn
from keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, CSVLogger, Callback
from keras.utils import Sequence, multi_gpu_model
import random
import sys
from multiprocessing import cpu_count
import numpy as np
import glob
from skimage.io import imread
import cv2
一些定义
epochs = sys.argv[0]
#epochs = 17
model_name = sys.argv[0]
#model_name = model_name
version = sys.argv[0]
num_classes = 35
batch_size = 16
stack_size = 64
DataLoader_video_train = DataLoader_video_train
DataLoader_video_test = DataLoader_video_test
class CustomModelCheckpoint(Callback):
def __init__(self, model_parallel, path):
super(CustomModelCheckpoint, self).__init__()
self.save_model = model_parallel
self.path = path
self.nb_epoch = 0
def on_epoch_end(self, epoch, logs=None):
self.nb_epoch += 1
self.save_model.save(self.path + str(self.nb_epoch) + '.hdf5')
i3d = i3d_modified(weights = 'rgb_imagenet_and_kinetics')
model = i3d.i3d_flattened(num_classes = num_classes)
optim = SGD(lr = 0.01, momentum = 0.9)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor = 0.1, patience = 10)
csvlogger = CSVLogger('i3d_'+model_name+'.csv')
model.compile(loss = 'categorical_crossentropy', optimizer = optim, metrics = ['accuracy'])
model_checkpoint = CustomModelCheckpoint(model, './weights_'+model_name+'/epoch_')
train_generator = DataLoader_video_train('/train_CS.txt',version, batch_size = batch_size)
test_generator = DataLoader_video_test('/test_CS.txt', version, batch_size = batch_size)
适配生成器
model.fit_generator(
generator = train_generator,
#validation_data=val_generator,
epochs = epochs,
steps_per_epoch = 17,
callbacks = [csvlogger, reduce_lr, model_checkpoint],
max_queue_size = 48,
workers = cpu_count() - 2,
use_multiprocessing = True,
)
print(model.evaluate_generator(generator = test_generator))
我收到以下错误
runfile('D:/Clones/i3d-master/i3d_train.py', wdir='D:/Clones/i3d-master')
Reloaded modules: i3d_inception
C:\Users\sancy\Anaconda3\lib\site-packages\keras\engine\training_generator.py:47: UserWarning: Using a generator with `use_multiprocessing=True` and multiple workers may duplicate your data. Please consider using the`keras.utils.Sequence class.
UserWarning('Using a generator with `use_multiprocessing=True`'
Traceback (most recent call last):
File "<ipython-input-8-8f7b9cc152d8>", line 1, in <module>
runfile('D:/Clones/i3d-master/i3d_train.py', wdir='D:/Clones/i3d-master')
File "C:\Users\sancy\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\sancy\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "D:/Clones/i3d-master/i3d_train.py", line 108, in <module>
use_multiprocessing = True,
File "C:\Users\sancy\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "C:\Users\sancy\Anaconda3\lib\site-packages\keras\engine\training.py", line 1418, in fit_generator
initial_epoch=initial_epoch)
File "C:\Users\sancy\Anaconda3\lib\site-packages\keras\engine\training_generator.py", line 174, in fit_generator
while epoch < epochs:
TypeError: '<' not supported between instances of 'int' and 'str'
我做错了什么? epoch < epochs
是什么意思?
Windows 10 蟒蛇 3.7.1 间谍:3.7
【问题讨论】:
也许可以尝试:epochs = int(sys.argv[0])
否则它可能被分配为 str
类型,这在您的进一步代码中不起作用。
当我这样做时得到了这个错误。 epochs = int(sys.argv[0]) ValueError: invalid literal for int() with base 10: 'D:/Clones/i3d-master/i3d_train.py'
您应该使用sys.argv[1]
而不是sys.argv[0]
,因为sys.argv[0]
始终是脚本名称。如果您有更多选项,那么您将需要[2]
、[3]
等。请参阅print( sys.argv )
和print( len(sys.argv) )
。但为此使用模块argparse
可能更安全。
谢谢!当我使用sys.argv[1]
时,我得到了这个File "D:/Clones/i3d-master/i3d_train.py", line 27, in <module> epochs = sys.argv[1] IndexError: list index out of range
。我会尝试使用argparse
这能回答你的问题吗? Python function error : '<' not supported between types 'str' and 'int'
【参考方案1】:
你是如何运行代码的?查看 Github repo,它需要 3 个参数
i3d_train.py
epochs = int(sys.argv[1])
model_name = sys.argv[2]
version = sys.argv[3]
finetune.sh
export PATH=/home/sdas/anaconda2/bin:$PATH
module load cuda/8.0 cudnn/5.1-cuda-8.0 opencv/3.4.1
mkdir -p weights_$2
python ./i3d_train.py $1 $2 $3
在终端上,你应该像这样运行它
python ./i3d_train.py <epochs> <model_name> <version>
【讨论】:
我的错。谢谢。【参考方案2】:这也可能由于以下链接中引用的兼容性问题而发生。
在初始化优化器时,您应该使用learning_rate
而不是lr
。这解决了我的错误。
https://github.com/tensorflow/tensorflow/blob/fcc4b966f1265f466e82617020af93670141b009/tensorflow/python/keras/optimizer_v2/adam.py#L362-L363
【讨论】:
以上是关于如何解决 TypeError:'int' 和 'str' 的实例之间不支持'<'?的主要内容,如果未能解决你的问题,请参考以下文章
为啥我收到 TypeError: unsupported operand type(s) for -: 'str' and 'int'
TypeError: 不支持的操作数类型 -: 'int' 和 'list'
TypeError:无法将'int'对象隐式转换为str(python)
TypeError: %: 'list' 和 'int' 不支持的操作数类型 |很有趣的案例?