python稀疏矩阵scipy.sparse中的csr_matrix及astype('category')

本文详细介绍使用Python的Pandas库进行数据编码和标签映射的方法,以及如何利用Scipy的CSR矩阵进行高效的数据存储与索引。通过具体实例展示了Pandas在数据处理中的灵活性,及CSR矩阵在稀疏数据存储方面的优势。

1、python astype(‘category’), 编码和标签对应,categories 和 code 映射为字典

import pandas as pd
 
# 创建数据集
df = pd.DataFrame.from_dict(
            {
            'col1': ['A', 'B', 'C', 'B', 'A', 'D'],
            'col2': ['aa', 'bb', 'bb', 'aa', 'dd', 'dd'],
            'col3': ['yes', 'yes','no','no','yes','yes']
            }
            ,orient='columns')
# df 
#   col1 col2 col3
# 0    A   aa  yes
# 1    B   bb  yes
# 2    C   bb   no
# 3    B   aa   no
# 4    A   dd  yes
# 5    D   dd  yes
 
# 转换为分类数据
df = df.astype('category') # 可以指定特定的列转为分类数据 df['col1'] = df['col1'].astype('category')
 
# 将标签数据转换为编码
df_code = pd.DataFrame({col: df[col].cat.codes for col in df}, index=df.index)
 
# df_code 
#    col1  col2  col3
# 0     0     0     1
# 1     1     1     1
# 2     2     1     0
# 3     1     0     0
# 4     0     2     1
# 5     3     2     1
 
# 将编码和标签一一对应,转为字典,方便查询
df_code_dict = {col: {code: category for code, category in enumerate(df[col].cat.categories)} for col in df}
# df_code_dict 
# {'col1': {0: 'A', 1: 'B', 2: 'C', 3: 'D'},
#  'col2': {0: 'aa', 1: 'bb', 2: 'dd'},
#  'col3': {0: 'no', 1: 'yes'}}

2.1、csr_matrix索引方式1

这种方式百度介绍的较多
indptr = np.array([0, 2, 3, 6])
indices = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()

输出:
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])
csr中的r表示row,即为行优先。

indptr中的元素两个两个的看,前两个为0和2,表示第一行有2-0=2个元素,再在indices中选前两个元素,得到在列上的位置为0和2,填充data的元素为1和2。接在是indptr中的2和3,所以第二行有3-2=1个元素,要填充的列位置是indices 中的2,元素从data中找为3. 在接下来是indptr中的3和6,表示第三行有6-3=3个元素,要填充的位置是indices 中的0、1、2,元素从data中找为4,5,6.

2.1、csr_matrix索引方式2

根据矩阵值进行索引

df = pd.DataFrame.from_dict(
            {
            'col1': [1, 0, 2, 3, 2, 1],
            'col2': [1, 0, 1, 2, 3, 4],
            'col3': [14, 15, 10, 20, 30, 40]
            }
            ,orient='columns')
df

在这里插入图片描述

sparse_item_user = sparse.csr_matrix((df['col3'], (df['col1'], df['col2'])))
sparse_item_user.toarray()

在这里插入图片描述

import pandas as pd import pymc as pm import numpy as np import pytensor.tensor as pt from scipy.sparse import csr_matrix # 加载数据 data = pd.read_excel('C:/Users/zyt/Desktop/操作.xlsx') # 使用 pivot_table 将数据换为矩阵形式 matrix = pd.pivot_table( data, values='发病数', # 用作矩阵值的列 index='地区', # 行索引:地区名 columns='年份', # 列索引:年份 fill_value=0 # 填充缺失值为 0 ) # 获取数值数据 data_numeric = matrix.values # 31 × 16 的二维数组 # 加载邻接矩阵 adjacency_matrix = pd.read_excel('C:/Users/zyt/Desktop/33.xlsx', header=None).values # 修复邻接矩阵 adjacency_matrix = np.maximum(adjacency_matrix, adjacency_matrix.T) # 强制对称化 np.fill_diagonal(adjacency_matrix, 0) # 清理对角线 adjacency_matrix = (adjacency_matrix > 0).astype(int) # 确保元素为 0 或 1 # 换为稀疏矩阵 W_sparse = csr_matrix(adjacency_matrix) # 构建贝叶斯时空独立模型 with pm.Model() as spatiotemporal_model: # 时间效应:ARIMA(0, 1, 2) time_effect_diff = pm.AR("time_effect_diff", rho=[0, 0], sigma=1.0, shape=data_numeric.shape[1] - 1) time_effect = pm.Deterministic("time_effect", pt.concatenate([[0], pt.cumsum(time_effect_diff)])) # 空间效应:条件自回归模型 (CAR) num_regions = data_numeric.shape[0] # CAR 模型的均值和精度 tau = pm.Gamma("tau", alpha=2, beta=0.5) # 更窄的先验 mu = pm.Normal("mu", mu=0, sigma=0.1, shape=num_regions) # 缩小标准差 space_effect = pm.CAR("space_effect", mu=mu, W=W_sparse, alpha=0.5, tau=tau, shape=num_regions) # 总效应:时间和空间效应的叠加 total_effect = pm.Deterministic( "total_effect", space_effect[:, None] + time_effect[None, :] ) # 观测模型:正态分布 likelihood = pm.Normal("likelihood", mu=total_effect.T, sigma=1, observed=data_numeric.T) # MCMC采样 trace = pm.sample(draws=1000, tune=1000, cores=1, target_accept=0.5) # 计算时间效应的后验均值和标准差 posterior_mean_time_effect = trace.posterior["time_effect"].mean(dim=("chain", "draw")) posterior_std_time_effect = trace.posterior["time_effect"].std(dim=("chain", "draw")) print("Time Effect Posterior Mean:", posterior_mean_time_effect) print("Time Effect Posterior Std:", posterior_std_time_effect) 此代码的后验抽样应用的是哪个算法
最新发布
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值