【问题标题】:Fixing probabilities, which do not sum to 1 in the matrix of words固定概率,在单词矩阵中总和不为 1
【发布时间】:2020-07-27 03:37:18
【问题描述】:

我创建了一个矩阵,使用这些问题的答案 - question 1question 2。关于此错误的类似问题无助于解决。

但概率超过 1 - ValueError: probabilities do not sum to 1

请让我知道如何与您分享 df 的一部分以便重现性。

我使用此代码生成了并发矩阵

# Create matrix
my_df = pd.DataFrame(0, columns = words, index = words)
for k,v in frequency_list.items():
my_df.at[k[0],k[1]] = v

这给了我 10000*10000 的矩阵。

然后我转换成频率

row_sums = my_df.values.sum(axis = 1)
row_sums[row_sums == 0] = 1
my_prob = my_df/row_sums.reshape((-1,1)) 
my_prob

当我打印一个单词时

my_prob.sum().tail(30)

我的概率高于 1。

“thy               0.000000
“till              0.002538
**“to              1.109681**

试图归一化

选择单词 the 并生成一个列表

word_the = my_string_prob['the'].tolist()

尝试归一化概率

sum_of_elements = sum(word_the)
a = 1/sum_of_elements
my_probs_scaled = [e*a for e in word_the]
my_probs_scaled
sum(my_probs_scaled)
### Output 1.000000000000005

这段代码在一个较小的矩阵上工作,在上述问题之一中它不是那么大和复杂。 谢谢!

【问题讨论】:

  • 你可以使用from decimal import Decimal as D来避免浮点错误
  • @ParthShah,谢谢在我的代码中使用它的任何提示?谢谢!

标签: python numpy matrix probability


【解决方案1】:

您可以在 python 中使用小数控制浮点数的精度。以以下为例:

from decimal import Decimal as D
from decimal import getcontext
getcontext().prec = 8

word_the = [9, 4, 5, 4]
sum_of_elements = sum(word_the)
a = D(1/sum_of_elements)
my_probs_scaled = [D(e)*a for e in word_the]
print(my_probs_scaled)
print(sum(my_probs_scaled))

输出是:

[Decimal('0.40909091'), Decimal('0.18181818'), Decimal('0.22727273'), Decimal('0.18181818')]
1.0000000

您可以随意调整参数,包括精度。

【讨论】:

  • TypeError: *: 'float' 和 'decimal.Decimal' 的操作数类型不受支持
  • 在我的机器上工作。奇怪的。正在编辑,您可以再试一次。
  • 十进制('0E-55'),十进制('0E-55'),十进制('0E-55'),十进制('0E-55'),十进制('0E-55 '), Decimal('0E-55'), Decimal('0.0030873908')] 1.0000004 - 如您所见,这次有效,但仍高于 1 :(
  • 是的,那是因为精度是 8。如果你把它降低到,比如说 6,它会起作用吗?
猜你喜欢
  • 2018-05-05
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
相关资源
最近更新 更多