Пример #1
0
def my_model(features, labels, mode, params):
	
	predictions, attn_weights = predict(features, params, transformer)
	estimator_spec = tf.estimator.EstimatorSpec(mode,  predictions={"predictions":predictions})
  
	print(transformer.summary())
	return estimator_spec
def main():
    # Basic usage: python predict.py /path/to/image checkpoint
    parser = argparse.ArgumentParser(description='Optional add-ons.')
    parser.add_argument('image_filepath')
    parser.add_argument('checkpoint')
    parser.add_argument('--topk', action='store', type=int)
    parser.add_argument('--gpu', action='store_true')
    parser.add_argument('--category_names', action='store') 
    args = parser.parse_args()
    
    topk = args.topk if args.topk else 1
    device = torch.device('cuda') if (args.gpu | torch.cuda.is_available()) else torch.device('cpu')
    
    # assign model from checkpoint
    model = ph.load_checkpoint(args.checkpoint, device)

    # assign predicted top "k" probabilities and classes
    probs, classes = ph.predict(args.image_filepath, model, topk)

    # get category class mapping to names for flowers
    if args.category_names:
        with open(args.category_names, 'r') as f:
            cat_to_name = json.load(f)
    # hard coded
    else:
        with open('cat_to_name.json', 'r') as g:
            cat_to_name = json.load(g)

    # convert class ID to a category name
    cat_class = cat_to_name[classes[0]]
    
    print('Flower Name: ', cat_class)
    print('Top Probability(ies): ', probs[:args.topk])
Пример #3
0
parser.add_argument("--gpu", help="Will you like to predict on gpu", action="store_true", default=False)

# Parse all the arguments
args = parser.parse_args()

# Extract parameters
image_dir = args.image_dir
checkpoint = args.checkpoint
top_k = int(args.top_k) if args.top_k else 1

# Process Image
image = predict_helper.process_image(image_dir)

# Load model from checkpoint
model, class_to_idx = predict_helper.load_checkpoint(checkpoint)

# Give image to model to predict output
top_prob, top_class = predict_helper.predict(image, model, class_to_idx, top_k, args.gpu)

# Check if the category names were provided so category names are printed instead
if args.category_names:
    # Read in the categories
    cat_to_name = predict_helper.read_category(args.category_names)
    new_class = []
    for i in top_class:
        new_class.append(cat_to_name[i])
        
    top_class = new_class

# Print the results
print("The model is ", top_prob*100, "% certain that the image has a predicted class of ", top_class)
Пример #4
0
from PIL import Image

in_args = phelp.get_input_args()
print(in_args)
with open(in_args.category_names, 'r') as f:
    cat_to_name = json.load(f)
imagepath = in_args.input
model_loaded = phelp.load_checkpoint(in_args.ckpdir, in_args.arch)
if in_args.gpu:
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    if (device == "cpu"):
        print("not found gpu,.... running on cpu")
else:
    device = "cpu"

probability, index = phelp.predict(imagepath,
                                   model_loaded,
                                   topk=in_args.topk,
                                   device=device)
pil_image = Image.open(imagepath)
folder = [
    model_loaded.class_to_idx[int(index[0][i])] for i in range(len(index[0]))
]
name = [cat_to_name[str(folder[i])] for i in range(len(folder))]
pb = list(probability[0].cpu().detach().numpy())
print("1 st class name={}...... Probability={}".format(name[0], pb[0]))
print("2 nd class name={}...... Probability={}".format(name[1], pb[1]))
print("3 rd class name={}...... Probability={}".format(name[2], pb[2]))
print("4 fth class name={}..... Probability={}".format(name[3], pb[3]))
print("5 fith class name={}.... Probability={}".format(name[4], pb[4]))
Пример #5
0
baseFilePath = "../../_analysis/" + directory + "/"
# print(baseFilePath + "\n")

# TODO: ordered dict in function?
segmentsDict = file_helper.getSegmentDict(baseFilePath)
#print("\n".join(segments))

# Loop segments
limit = 10
i = 0

for segment, segmentBasePath in segmentsDict.items():

  # Predict one segment
  segmentPngPath = segmentBasePath + ".png"
  score = predict_helper.predict(segmentPngPath, segment)
#  print(predictionDict)

  # Create report and cleanup
  if (score >= threshold):
    segmentPrint = segment + " " + str(score) + "\n"
    print(segmentPrint) # debug
    html += segmentPrint
    html += report_helper.audioEmbed(segment)
    html += report_helper.spectrogram(segment)    
  else:
    print(segment + " below threshold")

  # ELSE delete PNG & MP3

  # Limit how many segments handled (debug)
Пример #6
0
        segmentMeta["file_id"] = fileId
        segmentMeta["fileDirectory"] = directory

        segmentMeta["segmentStartUTC"] = fileData[
            "recordDateStartUTC"] + datetime.timedelta(
                0, segmentMeta["segmentStartSeconds"])

        if onlyAnalyse:
            print(segmentMeta)  # debug

            spectroFilePath = "../.." + rootDirectory + "/" + segmentMeta[
                "fileDirectory"] + "/" + segmentMeta["spectroFilename"]

            print(", PATH: " + spectroFilePath)  # debug

            score = predict_helper.predict(spectroFilePath,
                                           segmentMeta["spectroFilename"])

            if score >= threshold:
                print("above " + str(score) + "\n")
                #        html += "\n\n" + segmentMeta["baseAudioFilename"] + "\n"
                report.addPositiveSegment(segmentMeta, score)

            else:
                print("below " + str(score) + "\n")
                report.addNegativeSegment(score)
                mp3FilePath = "../.." + rootDirectory + "/" + segmentMeta[
                    "fileDirectory"] + "/" + segmentMeta["finalAudioFilename"]
                os.remove(mp3FilePath)
                os.remove(spectroFilePath)

        # If analyzing, skip saving to database.
Пример #7
0
my_parser.add_argument('checkpoint_path',
                       metavar='checkpoint_path',
                       type=str,
                       help='the checkpoint_path where model is saved')

my_parser.add_argument('--top_k', action='store', type=int, default=5)
my_parser.add_argument('--category_names',
                       action='store',
                       type=str,
                       default='./cat_to_name.json')
my_parser.add_argument('--gpu', action='store_true')

# Execute the parse_args() method
args = my_parser.parse_args()

path_to_image = args.path_to_image
checkpoint_path = args.checkpoint_path
top_k = args.top_k
category_names = args.category_names
gpu = args.gpu
print(args)

if not os.path.exists(path_to_image):
    print('The path_to_image specified does not exist')
    sys.exit()
if not os.path.exists(checkpoint_path):
    print('The checkpoint_path specified does not exist')
    sys.exit()

predict_helper.predict(path_to_image, checkpoint_path, top_k, category_names,
                       gpu)