humphd / have-fun-with-machine-learning

An absolute beginner's guide to Machine Learning and Image Classification with Neural Networks
Other
5.07k stars 541 forks source link

Inference Result is different between DIGITS(WEB) and Python Code #24

Open killeress opened 4 years ago

killeress commented 4 years ago

1.Digit Result

git_1

2.Python Result From This Tutorial

Here is my code

import numpy as np import sys import os

caffe_root = '/opt/caffe/' sys.path.insert(0, os.path.join(caffe_root, 'python'))

import caffe from caffe.proto import caffe_pb2

caffe.set_mode_gpu() model_dir = 'model' deploy_file = os.path.join(model_dir, 'deploy.prototxt') weights_file = os.path.join(model_dir, 'snapshot_iter_64980.caffemodel') net = caffe.Net(deploy_file, caffe.TEST, weights=weights_file)

transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) transformer.set_transpose('data', (2, 0, 1)) transformer.set_raw_scale('data', 255) transformer.set_channel_swap('data', (2, 1, 0))

mean_file = os.path.join(model_dir, 'mean.binaryproto') with open(mean_file, 'rb') as infile: blob = caffe_pb2.BlobProto() blob.MergeFromString(infile.read()) if blob.HasField('shape'): blob_dims = blob.shape assert len(blob_dims) == 4, 'Shape should have 4 dimensions - shape is %s' % blob.shape elif blob.HasField('num') and blob.HasField('channels') and \ blob.HasField('height') and blob.HasField('width'): blob_dims = (blob.num, blob.channels, blob.height, blob.width) else: raise ValueError('blob does not provide shape or 4d dimensions') pixel = np.reshape(blob.data, blob_dims[1:]).mean(1).mean(1) transformer.set_mean('data', pixel) labels_file = os.path.join(model_dir, 'labels.txt') labels = np.loadtxt(labels_file, str, delimiter='\n')

image = caffe.io.load_image('test_img.jpg')

net.blobs['data'].data[...] = transformer.preprocess('data', image)

out = net.forward()

softmax_layer = out['softmax']

LLPM_prob = softmax_layer.item(0) OK_prob = softmax_layer.item(1) YSBD_prob = softmax_layer.item(2) YSCQ_prob = softmax_layer.item(3)

print(LLPM_prob) print(OK_prob) print(YSBD_prob) print(YSCQ_prob) `

My Python Result:

4.98672634421e-05 0.00573868537322 0.993777871132 0.000433590757893