import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
data = [['西红柿', '排骨', '鸡蛋'],
['西红柿', '茄子'],
['鸡蛋', '袜子'],
['西红柿', '排骨', '茄子'],
['西红柿', '排骨', '袜子', '酸奶'],
['鸡蛋', '茄子', '酸奶'],
['排骨', '鸡蛋', '茄子'],
['土豆', '鸡蛋', '袜子'],
['西红柿', '排骨', '鞋子', '土豆']]
data = [list(set(d)) for d in data]
# 获取所有可能出现的物品
items=['土豆','排骨','茄子','袜子','西红柿','酸奶','鞋子','鸡蛋']
te = TransactionEncoder()
data = te.fit_transform(data, sparse=False).astype(int)# data = te.fit_transform(data)
df1 = pd.DataFrame(data, columns=te.columns_)
df = df1.reset_index(drop=True).rename(columns={'index': 'I'})
df.insert(0, 'ID', ['I{}'.format(i) for i in range(1, len(df)+1)])
df = df.reset_index(drop=True)
df.columns.name = None
print(df)
# 计算关联规则
rules = [('西红柿','排骨'), ('排骨','西红柿'), ('袜子','鸡蛋'),
('茄子','排骨'), ('茄子','西红柿'), ('茄子','鸡蛋')]
from mlxtend.frequent_patterns import apriori, association_rules
# 计算频繁项集
freq_itemsets = apriori(df1, min_support=0.2, use_colnames=True)
# 计算关联规则
rules = association_rules(freq_itemsets, metric="confidence", min_threshold=0.5)
rules = rules.sort_values(by=['confidence'], ascending=False)
pd.options.display.float_format = '{:.6f}'.format
# 输出结果
print(rules[['antecedents', 'consequents', 'support', 'confidence']])
您好,这个警告无法去掉,只能被忽略吧,给你一个忽略的方法,但是我并不建议忽略这些因为这对于调试解决问题很重要。
忽略警告,可以使用warnings模块,设置忽略选项,如下代码所示。
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
当然,也可以使用filterwarnings
函数直接把消息过滤掉,看你选择哪一种了,都可以。
import warnings
warnings.filterwarnings("ignore", message="DataFrames with non-bool types")
是不是您鞋子和鸡蛋没数据造成的警告⚠️
可以去除那两列试试看。
解决方案:
DeprecationWarning警告提示某个功能已经被弃用或将来会被废弃,因为它已经不再是一个最佳的解决方案,或者存在其他更好的方法来完成相同的任务。它的意思是,建议你改变你的代码来避免使用这个功能,以免在未来的版本中出现不兼容问题。
在这个例子中,警告提示使用非bool类型的DataFrame可能会导致更差的计算性能,并且在未来的版本中可能不再支持。
根据警告信息,我们需要使用bool类型的DataFrame来代替原来的DataFrame对象。可以通过将DataFrame转换为bool类型的DataFrame来实现。例如,可以使用以下代码将DataFrame转换为bool类型:
df = df.astype(bool)
在这个例子中,如果我们在fpcommon.py文件的110行执行上述代码,可以解决DeprecationWarning警告。具体来说,可以使用以下方法:
import pandas as pd
from mlxtend.frequent_patterns import fpcommon
def fp_growth(df, **kwargs):
"""Find frequent itemsets in the provided DataFrame using the FP-growth algorithm.
Parameters
----------
df : pandas DataFrame, sparse matrix (CSR), transaction-database format
(eg. [['A', 'B'], ['B', 'C']] or
[{0:"A", 1:"B"}, {1:"C", 2:"B", 3:"D"}, ...])
pandas DataFrame the encoded format. The allowed values are either 0/1 or True/False.
For example,
Apple Bananas Beer Chicken Milk Rice
0 True True False False False False
1 True True True False False False
2 True False True False True True
3 False True True True False True
4 False False True True True True
5 False False False True True True
6 True False True True False True
**kwargs :
Support for additional keyword arguments might be added to this function
in the future. For compatibility reasons, you should only use keyword
arguments that are defined in this function.
Returns
-------
pandas.DataFrame
A DataFrame of frequent itemsets including their support values (as
columns).
"""
if isinstance(df, pd.DataFrame):
# convert DataFrame to sparse matrix
sparse_df = df.to_sparse(fill_value=False)
# convert sparse matrix to transaction database
trn = _convert_sparse_matrix(sparse_df)
else:
# handle input format as transaction database
trn = df
patterns = fpcommon.fpgrowth(trn, **kwargs)
# convert patterns back to DataFrame
res_df = pd.DataFrame(patterns, columns=['support', 'itemsets'])
# convert itemsets back to frozensets
res_df['itemsets'] = res_df['itemsets'].apply(frozenset)
return res_df
该方法使用了DataFrame的astype()方法,将DataFrame对象转换为bool类型的DataFrame,从而避免了DeprecationWarning警告。