Verified Commit 5771ab16 authored by Kiryuu Sakuya's avatar Kiryuu Sakuya 🎵
Browse files

Add exam.9

parent 25a37697
import numpy as np
def softmax(x):
np.seterr(divide='ignore', invalid='ignore')
return (np.exp(x).T / np.sum(np.exp(x), axis=1)).T
def returnOneHot(Output):
'''
:param Output: 神经网络的输出
:return:
'''
out = np.zeros(Output.shape,dtype=np.int)
idx = Output.argmax(axis=1)
out[np.arange(Output.shape[0]), idx] = 1
return out
def computeAccuracy(pred,label):
'''
:param pred: 预测值
:param label: 实际值
:return:
'''
right = 0
for p,l in zip(pred,label):
if (p==l).all():
right+=1
return right/len(pred)
\ No newline at end of file
import numpy as np
def softmax(x):
'''
对输出的每一行(即对每个样本的各个标签上的值)做softmax变换
:param x: 一般是(batchSize,num_Labels), 是模型的输出
:return: 每一行经过了softmax处理之后的结果
'''
#********** Begin **********#
#********** End **********#
def returnOneHot(Output):
'''
softmax的输出不是onehot型的, 将最大概率处替换为1,其他位置均置为0
:param Output: 神经网络的输出
:return: onehot型的输出
'''
#********** Begin **********#
#********** End **********#
def computeAccuracy(pred,label):
'''
计算预测的正确率
:param pred: 预测的标签
:param label: 预测样本真实的标签
:return: 正确率
'''
#********** Begin **********#
#********** End **********#
from outputsUtilsForUsers import softmax as Softmax
from outputsUtilsForUsers import computeAccuracy as ComputeAccuracy
from outputsUtilsForUsers import returnOneHot as ReturnOneHot
#
# from outputsUtilsForUsers import softmax as Softmax
# from outputsUtilsForUsers import computeAccuracy as ComputeAccuracy
# from outputsUtilsForUsers import returnOneHot as ReturnOneHot
'''
测试矩阵:
[[-1 2 25 7]
[20 15 10 5]
[12 4 19 5]
[ 9 13 61 8]]
对应标签:
[[0 0 1 0]
[1 0 0 0]
[0 0 1 0]
[0 0 1 0]]
你softmax的值:
[[0. 0. 1. 0. ]
[0.993 0.007 0. 0. ]
[0.001 0. 0.999 0. ]
[0. 0. 1. 0. ]]
你onehot编码后的值:
[[0 0 1 0]
[1 0 0 0]
[0 0 1 0]
[0 0 1 0]]
你计算的准确率:
1.0
'''
import numpy as np
test_matrix = np.array([[-1,2,25,7],
[20,15,10,5],
[12,4,19,5],
[9,13,61,8],])
test_label = np.array([[0,0,1,0],
[1,0,0,0],
[0,0,1,0],
[0,0,1,0]])
print('测试矩阵:')
print(test_matrix)
print('对应标签:')
print(test_label)
softmaxed = Softmax(test_matrix)
print('你softmax的值:')
print(np.around(softmaxed,decimals=3))
onehoted = ReturnOneHot(softmaxed)
print('你onehot编码后的值:')
print(onehoted)
accuracy = ComputeAccuracy(onehoted,test_label)
print('你计算的准确率:')
print(accuracy)
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