我正在学习神经网络,我想cross_entropy在python中编写一个函数.在哪里定义为
其中N是样本的数目,k是类的数量,log是自然对数,t_i,j是1,如果样品i是在类j和0否则,和p_i,j是预测的概率的样品i是在类j.要避免使用对数的数字问题,请将预测剪辑到[10^{?12}, 1 ? 10^{?12}]范围.
根据上面的描述,我通过clippint预测[epsilon, 1 ? epsilon]范围来记下代码,然后根据上面的公式计算交叉熵.
def cross_entropy(predictions, targets, epsilon=1e-12):
"""
Computes cross entropy between targets (encoded as one-hot vectors)
and predictions.
Input: predictions (N, k) ndarray
targets (N, k) ndarray
Returns: scalar
"""
predictions = np.clip(predictions, epsilon, 1. - epsilon)
ce = - np.mean(np.log(predictions) * targets)
return ce
Run Code Online (Sandbox Code Playgroud)
以下代码将用于检查功能cross_entropy …
我有5个序列号的列表:
['123', '134', '234', '214', '223']
Run Code Online (Sandbox Code Playgroud)
我想获得每个数字的百分比1, 2, 3, 4在ith号码中的各个序列的位置.例如,这个数字序列的0th位置上5的数字是1 1 2 2 2,然后我需要计算
1, 2, 3, 4这个数字序列中的百分比并返回百分比作为0th新列表的元素.
['123', '134', '234', '214', '223']
0th position: 1 1 2 2 2 the percentage of 1,2,3,4 are respectively: [0.4, 0.6, 0.0, 0.0]
1th position: 2 3 3 1 2 the percentage of 1,2,3,4 are respectively: [0.2, 0.4, 0.4, 0.0]
2th position: 3 4 4 4 3 the percentage of …Run Code Online (Sandbox Code Playgroud) 我有一个数据框:
Y X1 X2 X3
1 1 0 1
1 0 1 1
0 1 0 1
0 0 0 1
1 1 1 0
0 1 1 0
Run Code Online (Sandbox Code Playgroud)
我想Y根据等于 的其他列对列中的所有行求和1,即sum(Y=1|Xi =1)。例如,对于列X1,s1 = sum(Y=1|Xi =1) =1 + 0 +1+0 =2
Y X1
1 1
0 1
1 1
0 1
Run Code Online (Sandbox Code Playgroud)
对于X2列,s2 = sum(Y=1|Xi =1) = 0 +1+0 =1
Y X2
0 1
1 1
0 1
Run Code Online (Sandbox Code Playgroud)
对于X3 …
我想根据空间分割一个字符串
a = ' girl\n is'
a.split()
['girl', 'is']
Run Code Online (Sandbox Code Playgroud)
我发现分裂后,'\n'也会消失.我想要的结果是
['girl\n', 'is']
Run Code Online (Sandbox Code Playgroud)
然后,如果我使用.splitlines方法,返回的结果也不是我想要的.
a.splitlines(True)
[' girl\n', ' is']
Run Code Online (Sandbox Code Playgroud)
你有什么建议吗?谢谢!