简体   繁体   English

从文件路径中删除目录

[英]Remove directory from filepath

I've made a convolutional neural network using Python and Keras.我使用 Python 和 Keras 制作了一个卷积神经网络。 I am testing my models on test sets with random number of images per class (1 folder containing x amount of images).我正在测试集上测试我的模型,每个 class(1 个包含 x 数量图像的文件夹)的图像数量是随机的。 I am able to get a data frame with the showing the file name for the image and the directory, and the prediction.我能够获得一个数据框,其中显示图像和目录的文件名以及预测。 I would like to remove the directory from the file name.我想从文件名中删除目录。 It shows random 350 images/dogs1.tif and I want it to just say dogs1.tif.它显示随机的 350 张图像/dogs1.tif,我希望它只显示 dog1.tif。

  #import my model
new_model = tf.keras.models.load_model('model folder')
#upload my test data
train_datagen = ImageDataGenerator(rescale=1./255)

test_batches = train_datagen.flow_from_directory(
        'folder containing random images',
        target_size=(224, 224),
        batch_size=10,
        classes = None,
        class_mode = None,
        shuffle = False)

#my prediction
predictions = new_model.predict(test_batches, steps=35, verbose=0)

#rounding my predctions
rounded_predictions = np.argmax(predictions, axis = -1)

#converting one hot encoded labels to categorical labels 
labels =["dog","cat","horse"]
names = [0,1,2]
labels_name = dict(zip(names, labels))

#joining them together
labels_name = dict((v,k) for k,v in labels_name.items())
predictions = [labels[k] for k in rounded_predictions]

#getting files names for the images
filenames= test_batches.filenames

#creating the dataframe
results=pd.DataFrame({"file":filenames,"pr":predictions})
#getting files names for the images
filenames= test_batches.filenames

filename_extr=[]
for i in filenames:
  filename_extr.append(os.path.basename(i))

#creating the dataframe
results=pd.DataFrame({"file":filename_extr,"pr":predictions})

Should do it.应该这样做。 (This (using a for loop) is just one way to do it. For sure there are plenty other ways.) (这(使用 for 循环)只是一种方法。当然还有很多其他方法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM