0
我是Keras和Tensorflow的新手。我正在使用深度學習來開展面部識別項目。我使用此代碼(輸出softmax圖層)將輸入主題的類標籤作爲輸出獲得,並且我的100個類的自定義數據集的準確率爲97.5%。如何使用keras和tensorflow後端將密集層的輸出作爲一個numpy數組?
但是現在我對特徵向量表示感興趣,所以我想通過網絡傳遞測試圖像並在softmax(最後一層)之前從激活的密集層提取輸出。我提到了Keras的文檔,但似乎沒有任何效果。任何人都可以請幫助我如何從密集層激活提取輸出並保存爲一個numpy數組?提前致謝。
class Faces:
@staticmethod
def build(width, height, depth, classes, weightsPath=None):
# initialize the model
model = Sequential()
model.add(Conv2D(100, (5, 5), padding="same",input_shape=(depth, height, width), data_format="channels_first"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))
model.add(Conv2D(100, (5, 5), padding="same"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))
# 3 set of CONV => RELU => POOL
model.add(Conv2D(100, (5, 5), padding="same"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))
# 4 set of CONV => RELU => POOL
model.add(Conv2D(50, (5, 5), padding="same"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format="channels_first"))
# 5 set of CONV => RELU => POOL
model.add(Conv2D(50, (5, 5), padding="same"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))
# 6 set of CONV => RELU => POOL
model.add(Conv2D(50, (5, 5), padding="same"))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), data_format="channels_first"))
# set of FC => RELU layers
model.add(Flatten())
#model.add(Dense(classes))
#model.add(Activation("relu"))
# softmax classifier
model.add(Dense(classes))
model.add(Activation("softmax"))
return model
ap = argparse.ArgumentParser()
ap.add_argument("-l", "--load-model", type=int, default=-1,
help="(optional) whether or not pre-trained model should be loaded")
ap.add_argument("-w", "--weights", type=str,
help="(optional) path to weights file")
args = vars(ap.parse_args())
path = 'C:\\Users\\Project\\FaceGallery'
image_paths = [os.path.join(path, f) for f in os.listdir(path)]
images = []
labels = []
name_map = {}
demo = {}
nbr = 0
j = 0
for image_path in image_paths:
image_pil = Image.open(image_path).convert('L')
image = np.array(image_pil, 'uint8')
cv2.imshow("Image",image)
cv2.waitKey(5)
name = image_path.split("\\")[4][0:5]
print(name)
# Get the label of the image
if name in demo.keys():
pass
else:
demo[name] = j
j = j+1
nbr =demo[name]
name_map[nbr] = name
images.append(image)
labels.append(nbr)
print(name_map)
# Training and testing data split ratio = 60:40
(trainData, testData, trainLabels, testLabels) = train_test_split(images, labels, test_size=0.4)
trainLabels = np_utils.to_categorical(trainLabels, 100)
testLabels = np_utils.to_categorical(testLabels, 100)
trainData = np.asarray(trainData)
testData = np.asarray(testData)
trainData = trainData[:, np.newaxis, :, :]/255.0
testData = testData[:, np.newaxis, :, :]/255.0
opt = SGD(lr=0.01)
model = Faces.build(width=200, height=200, depth=1, classes=100,
weightsPath=args["weights"] if args["load_model"] > 0 else None)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
if args["load_model"] < 0:
model.fit(trainData, trainLabels, batch_size=10, epochs=300)
(loss, accuracy) = model.evaluate(testData, testLabels, batch_size=100, verbose=1)
print("Accuracy: {:.2f}%".format(accuracy * 100))
if args["save_model"] > 0:
model.save_weights(args["weights"], overwrite=True)
for i in np.arange(0, len(testLabels)):
probs = model.predict(testData[np.newaxis, i])
prediction = probs.argmax(axis=1)
image = (testData[i][0] * 255).astype("uint8")
name = "Subject " + str(prediction[0])
if prediction[0] in name_map:
name = name_map[prediction[0]]
cv2.putText(image, name, (5, 20), cv2.FONT_HERSHEY_PLAIN, 1.3, (255, 255, 255), 2)
print("Predicted: {}, Actual: {}".format(prediction[0], np.argmax(testLabels[i])))
cv2.imshow("Testing Face", image)
cv2.waitKey(1000)
我得到這樣的輸出: *張量( 「dense_1/BiasAdd:0」,形狀=( ?,442),dtype = float32)* 但我需要打印一個numpy數組,它是輸入圖像的一個特徵表示。 – TheBiometricsGuy
在上面的例子中,X需要是一個numpy數組(即真實數據)。 keras model.predict()函數通過Tensorflow圖處理該數據並返回一個numpy數組。 「張量」類型是用於創建圖形的內部變量。你不應該看到這是來自model.predict()的輸出 – bivouac0