我正在训练具有七个类的基本图像分类器,并且在Fit中遇到Python错误,找不到其他人在谈论。
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from PIL import Image
import numpy as np
import os
imageSide = 256
def buildAndTrainNetwork():
classifier = Sequential()
classifier.add(Conv2D(32, (3, 3), input_shape = (imageSide, imageSide, 3), activation = 'relu', data_format="channels_last"))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 7, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
labelList = [('CarHatchback', [1,0,0,0,0,0,0]), ('CarMinivan', [0,1,0,0,0,0,0]), ('CarPickup', [0,0,1,0,0,0,0]), ('CarSaloon', [0,0,0,1,0,0,0]), ('CarSmart', [0,0,0,0,1,0,0]), ('CarSports', [0,0,0,0,0,1,0]), ('CarVan', [0,0,0,0,0,0,1])]
train_data = []
train_labels = []
test_data = []
for label,labelData in labelList:
dir = "mlData/train/" + label
for img in os.listdir(dir):
path = os.path.join(dir, img)
img = Image.open(path)
img = img.convert('RGB')
img = img.resize((imageSide, imageSide), Image.ANTIALIAS)
img = np.array(img)
train_data.append(img)
train_labels.append(labelData)
for label,labelData in labelList:
dir = "mlData/test/" + label
for img in os.listdir(dir):
path = os.path.join(dir, img)
img = Image.open(path)
img = img.convert('RGB')
img = img.resize((imageSide, imageSide), Image.ANTIALIAS)
img = np.array(img)
test_data.append(img)
train_data = np.array(train_data)
test_data = np.array(test_data)
train_labels = np.array(train_labels)
print("Training shape:")
print(train_data.shape)
print("Train labels shape:")
print(train_labels.shape)
print("Testing shape:")
print(test_data.shape)
classifier.fit(
train_data,
train_labels,
steps_per_epoch=8000,
epochs=10,
validation_data=test_data,
validation_steps=800
)
#
buildAndTrainNetwork()
我收到的错误是:
文件 “ /home/ian/.local/lib/python3.6/site-packages/keras/engine/training.py”, 1034行,适合 val_ins = val_ins,UnboundLocalError:分配前已引用本地变量“ val_ins”
仅供参考,形状输出为:
Training shape:
(3502, 256, 256, 3)
Train labels shape:
(3502, 7)
Testing shape:
(3506, 256, 256, 3)
我假设我没有正确格式化输入数据,但是我正在努力查看实际错误。
答案 0 :(得分:1)
validation_data
中的 classifier.fit
应该是一个元组,其中包含测试图像(您拥有)和测试标签,但您已忘记加载它们。
for label,labelData in labelList:
dir = "mlData/test/" + label
for img in os.listdir(dir):
# ...
test_data.append(img)
test_labels.append(labelData) # add this
然后
classifier.fit(
validation_data=(test_data, test_labels)
# ...
)