一些函数2

1、关于稀疏矩阵

import scipy.sparse as sp

sp.coo_matrix()     

全称:A sparse matrix in COOrdinate format.    

coo_matrix((data, (i,j)), [shape=(M,N)], dtype=np.int32)

(i,j)为目标位置,将此位置的值改为data对应的值,整个稀疏矩阵大小为(M,N),其余位置为0。

eg. 根据结点信息连接生成邻接矩阵。

adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),
                        shape=(labels.shape[0], labels.shape[0]),
                        dtype=np.float32)

sp.csr_matrix()

全称:Compressed Sparse Row matrix

csr_matrix((data, indices, indptr), [shape=(M,N)]

官方解释:is the standard CSR representation where the column indices for row i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are stored in data[indptr[i]:indptr[i+1]]. If the shape parameter is not supplied, the matrix dimensions are inferred from the index arrays.

 按行确定稀疏矩阵中非0值及其位置。

eg. a = [[0, 1, 2], [4, 2, 0], [0, 1, 0]]

a.indptr    [0, 2, 4, 5]          a.indices    [1, 2, 0, 1, 1]           a.data      [1, 2, 4, 2, 1] 

第一行:a.indptr[0]为0,a.indptr[1]为2,所以第一行非0值的位置储存在a.indices[0:2]中,即1, 2;对应的值储存在a.data[0:2]中,即1, 2;所以第一行为[0, 1, 2],之后的行以此类推。

a.tocoo()

将csr表示形式转换为coo。

import scipy.sparse as sp
import numpy as np
b = np.array([[0, 1, 2], [4, 2, 0], [0, 1, 0]])
# 将稀疏矩阵用此种方法表示,后续仍可以直接对矩阵进行操作
a = sp.csr_matrix(b, dtype=np.float32)     
c = a.tocoo().astype(np.float32)

2、计算准确率

def accuracy(output, labels):
    preds = output.max(1)[1].type_as(labels)    # 将预测结果转换为和labels一致的类型
    correct = preds.eq(labels).double()
    correct = correct.sum()
    return correct / len(labels)

output需要为torch数组

b = np.array([[0, 1, 2], [4, 2, 0], [0, 1, 0]])
b = torch.from_numpy(b)
a = b.max(1)
print(a)

-----------------------------
torch.return_types.max(
values=tensor([2, 4, 1], dtype=torch.int32),
indices=tensor([2, 0, 1]))

按行取最大值并返回一个元组,依次包含每行最大值和所在行中的位置。使用output.max(1)[1]可以取出最大值位置数组。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值