Commit 172e0b44 authored by Gihan Jayatilaka's avatar Gihan Jayatilaka

visualize-2

parent 0b9e4680
DEBUG=True
#python visualize-2.py results-video.npz
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
import sys
import math
import scipy.signal
CELLS_PER_FRAME=0
SQRT_CELLS=0
if __name__ == '__main__':
RESULT_FILE_NAME=sys.argv[1]
CELLS_PER_FRAME=(int(sys.argv[2]))
SQRT_CELLS=math.sqrt(CELLS_PER_FRAME)
data=np.load(RESULT_FILE_NAME)
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
#classes = classes[unique_labels(y_true, y_pred)]
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
plt.show()
return ax
def convolve2D(X,Y,XY):
# XY=XY
# if XY == None:
# XY=np.zeros(shape=(X.shape[0]-Y.shape[0]+1,X.shape[1]-Y.shape[1]+1),dtype=np.int32)
for i in range(XY.shape[0]):
for j in range(XY.shape[1]):
if DEBUG:
print("DEBUG: convs X ",X[i:i+Y.shape[0],j:j+Y.shape[0]])
print("DEBUG: convs Y ",Y)
XY[i,j]=np.sum(np.sum(X[i:i+Y.shape[0],j:j+Y.shape[0]] * Y))
if DEBUG: print("DEBUG",i,j,XY[i,j])
return XY
def test_convolve2D():
X=np.arange(16).reshape((4,4))
Y=(2**np.arange(4)).reshape((2,2))
#Z=convolve2D(X,Y)
print("X",X)
print("Y",Y)
#print("Conv X,Y=",Z)
ZZ=np.zeros((3,3))
convolve2D(X,Y,ZZ)
print("Conv X,Y=",ZZ)
def countMisses(yTrue,yPred,windowH,windowW):
global SQRT_CELLS
truePred=np.zeros(shape=(windowH*windowW,windowH*windowW),dtype=np.int32)
yTrue=np.reshape(yTrue,(yTrue.shape[0],SQRT_CELLS,SQRT_CELLS))
yPred=np.reshape(yPred,(yPred.shape[0],SQRT_CELLS,SQRT_CELLS))
convKer=np.zeros((windowH,windowW),dtype=np.int32)
convKer=np.arange(windowH*windowW).reshape((windowH,windowW))
convTrue=np.zeros((yTrue.shape[0],SQRT_CELLS-windowH+1,SQRT_CELLS-windowW+1))
convPred=np.zeros((yPred.shape[0],SQRT_CELLS-windowH+1,SQRT_CELLS-windowW+1))
convTrue=np.zeros((yTrue.shape[0],SQRT_CELLS-windowH+1,SQRT_CELLS-windowW+1), dtype=np.int32)
convPred=np.zeros((yPred.shape[0],SQRT_CELLS-windowH+1,SQRT_CELLS-windowW+1), dtype=np.int32)
for f in range(yTrue.shape[0]):
convTrue[f]=scipy.signal.convolve2d(yTrue[f],convKer,mode='valid')
convolve2D(yTrue[f],convKer,convTrue[f])
for f in range(yPred.shape[0]):
convPred[f]=scipy.signal.convolve2d(yPred[f],convKer,mode='valid')
convolve2D(yPred[f],convKer,convPred[f])
if DEBUG:
print("convTrue shape={}, convPred shape={}".format(convTrue.shape,convPred.shape))
convTrue=convTrue.flatten()
convPred=convPred.flatten()
print(convPred)
print(convTrue)
if DEBUG:
print("convTrue shape={}, convPred shape={}".format(convTrue.shape,convPred.shape))
plot_confusion_matrix(convTrue,convPred,np.arange(2**(windowH*windowW)))
'''for y in range(convTrue.shape[0]):
for x in range(convTrue.shape[1]):
truePred[convTrue[y,x],convPred[y,x]]+=1
print(truePred)'''
def drawTrainingHistograms(data):
def drawTrainingHistograms(data,VID,FIG,CAPTION):
global SQRT_CELLS
VID='cropped-tvstatic-video'
FIG_NAME='{}-{}x{}-inception'.format(VID,SQRT_CELLS,SQRT_CELLS)
TITLE='{}-{}x{}->inception'.format(VID,SQRT_CELLS,SQRT_CELLS)
CAPTION=" inception v3 network"
#CAPTION=" inception v3 network"
FIG_NAME='./fig/'+FIG_NAME+'.png'
FIG_NAME='./fig/'+FIG+'.png'
trc=data['trainCost']
tra=data['trainAcc']
tec=data['testCost']
tea=data['testAcc']
print("Train cost: ",data['trainCost'])
print("Test cost: ",data['testCost'])
print("Train acc: ",data['trainAcc'])
print("Test acc: ",data['testAcc'])
#print(np.array(tra)-np.array(tea))
EPOCHS=len(trc)
......@@ -98,3 +199,43 @@ def drawTrainingHistograms(data):
if __name__ == '__main__':
# test_convolve2D()
if True:
RESULT_FILE_NAME=sys.argv[1]
CELLS_PER_FRAME=(int(sys.argv[2]))
SQRT_CELLS=int(math.sqrt(CELLS_PER_FRAME))
data=np.load(RESULT_FILE_NAME)
MODE=sys.argv[3]
if MODE=='histogram' or MODE=='hist':
vidName=sys.argv[4]
fileName=sys.argv[5]
CAPTION=""
for x in range(6,len(sys.argv)):
CAPTION=CAPTION+" "+sys.argv[x]
drawTrainingHistograms(data,vidName,fileName,CAPTION)
elif MODE=='analyze':
codeH=int(sys.argv[4])
codeW=int(sys.argv[5])
countMisses(data['yTrueTest'],data['yPredTest'], codeH, codeW)
else:
_=sys.argv[10000]#Just looking for something to give an error
if False:
print("python visualize-2.py res.npz 100 hist multivid multivid-with-inception")
print("python visualize-2.py res.npz 100 analyze 2 2")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment