我正在尝试建立对象定位算法,该算法将在图像加载到边界框时返回其坐标:
class DataGenerator(Sequence):
def __init__(self, csv_file):
self.paths = []
with open(csv_file, "r") as file:
self.coords = np.zeros((sum(1 for line in file), 4))
file.seek(0)
reader = csv.reader(file, delimiter=",")
next(reader)
for index, row in enumerate(reader):
for i, r in enumerate(row[1:5]):
row[i+1] = int(r)
path,x0, x1, y0, y1= row
self.coords[index, 0] = x0 * IMAGE_SIZE / image_width
self.coords[index, 1] = y0 * IMAGE_SIZE / image_height
self.coords[index, 2] = (x1 - x0) * IMAGE_SIZE / image_width
self.coords[index, 3] = (y1 - y0) * IMAGE_SIZE / image_height
path="C:/Users/Avinash/Downloads/flipkart_images/images/"+path
self.paths.append(path)
def __len__(self):
return math.ceil(len(self.coords) / BATCH_SIZE)
def __getitem__(self, idx):
batch_paths = self.paths[idx * BATCH_SIZE:(idx + 1) * BATCH_SIZE]
batch_coords = self.coords[idx * BATCH_SIZE:(idx + 1) * BATCH_SIZE]
#print(batch_coords)
batch_images = np.zeros((len(batch_paths), IMAGE_SIZE, IMAGE_SIZE, 3), dtype=np.float32)
for i, f in enumerate(batch_paths):
img = Image.open(f)
img = img.resize((IMAGE_SIZE, IMAGE_SIZE))
img = img.convert('RGB')
batch_images[i] = preprocess_input(np.array(img, dtype=np.float32))
img.close()
return batch_images, batch_coords
def create_model(trainable=False):
model = MobileNetV2(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), include_top=False, alpha=ALPHA)
for layer in model.layers:
layer.trainable = trainable
x = model.layers[-1].output
x = Conv2D(4, kernel_size=3, name="coords")(x)
#x = BatchNormalization()(x)
#x = Activation("relu")(x)
x = Reshape((4,))(x)
return Model(inputs=model.input, outputs=x)
model = create_model()
model.summary()
train_datagen = DataGenerator(TRAIN_CSV)
model.compile(loss="mean_squared_error", optimizer="adam", metrics=["accuracy"])
model.summary()
model.fit_generator(generator=train_datagen,epochs=5,verbose=1,shuffle=True)
error:
Epoch 1/5
350/438 [======================>.......]ETA: 1:49 loss: 101.0604 - acc:
0.8517
即使模型开始训练,它也会在middel中停止,并且每次都以某个随机数停止,即使没有随机播放命令,它也会在随机数处停止并显示以下错误
ValueError Traceback (most recent call last)
<ipython-input-29-3897d22efcea> in <module>()
1 model.summary()
2
----> 3
model.fit_generator(generator=train_datagen,epochs=5,verbose=1,shuffle=True)
~\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in
fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks,
validation_data, validation_steps, class_weight, max_queue_size, workers,
use_multiprocessing, shuffle, initial_epoch)
2175 use_multiprocessing=use_multiprocessing,
2176 shuffle=shuffle,
-> 2177 initial_epoch=initial_epoch)
2178
2179 def evaluate_generator(self,
~\Anaconda3\lib\site-
packages\tensorflow\python\keras\engine\training_generator.py in
fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks,
validation_data, validation_steps, class_weight, max_queue_size, workers,
use_multiprocessing, shuffle, initial_epoch)
174
175 outs = model.train_on_batch(
--> 176 x, y, sample_weight=sample_weight,
class_weight=class_weight)
177
178 if not isinstance(outs, list):
~\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in
train_on_batch(self, x, y, sample_weight, class_weight)
1926 # Validate and standardize user data.
1927 x, y, sample_weights = self._standardize_user_data(
-> 1928 x, y, sample_weight=sample_weight,
class_weight=class_weight)
1929
1930 if context.executing_eagerly():
~\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in
_standardize_user_data(self, x, y, sample_weight, class_weight, batch_size,
check_steps, steps_name, steps, validation_split)
990 x, y, sample_weight = next_element
991 x, y, sample_weights = self._standardize_weights(x, y,
sample_weight,
--> 992 class_weight,
batch_size)
993 return x, y, sample_weights
994
~\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in
_standardize_weights(self, x, y, sample_weight, class_weight, batch_size)
1167 # Check that all arrays have the same length.
1168 if not self._distribution_strategy:
-> 1169 training_utils.check_array_lengths(x, y, sample_weights)
1170 if self._is_graph_network and not
context.executing_eagerly():
1171 # Additional checks to avoid users mistakenly using
improper loss fns.
~\Anaconda3\lib\site-
packages\tensorflow\python\keras\engine\training_utils.py in
check_array_lengths(inputs, targets, weights)
424 'the same number of samples as target arrays. '
425 'Found ' + str(list(set_x)[0]) + ' input samples '
--> 426 'and ' + str(list(set_y)[0]) + ' target samples.')
427 if len(set_w) > 1:
428 raise ValueError('All sample_weight arrays should have '
ValueError: Input arrays should have the same number of samples as target
arrays. Found 16 input samples and 17 target samples.
您可以看到该模型开始训练并突然停止 出现此错误。