【TensorFlow】稀疏矢量

SparseTensor与SparseTensorValue的理解

SparseTensor(indices, values, dense_shape)

稀疏矢量的表示

  • indices shape为[N, ndims]的2-D int64矢量,用以指定非零元素的位置,比如indices=[[1,3], [2,4]]表示[1,3]和[2,4]位置的元素为非零元素。
  • values shape为[N]的1-D矢量,对应indices所指位置的元素值
  • dense_shape shape为[ndims]的1-D矢量,代表稀疏矩阵的shape
SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])
>>
[[1, 0, 0, 0]
 [0, 0, 2, 0]
 [0, 0, 0, 0]]

SparseTensor(indices=[[0], [3]], values=[4, 6], dense_shape=[7])
>>[4, 0, 0, 6, 0, 0, 0]

稀疏矢量的封装并不直观,可以通过稀疏矢量的方式构建矢量(sparse_to_dense)或者将稀疏矢量转换成矢sparse_tensor_to_dense量的方式来感受一下:

def sparse_to_dense(sparse_indices,
                    output_shape,
                    sparse_values,
                    default_value=0,
                    validate_indices=True,
                    name=None)
  • sparse_indices sparse_indices:稀疏矩阵中那些个别元素对应的索引值。
    • sparse_indices是个数,那么它只能指定一维矩阵的某一个元素
    • sparse_indices是个向量,那么它可以指定一维矩阵的多个元素
    • sparse_indices是个矩阵,那么它可以指定二维矩阵的多个元素
  • output_shape 输出的稀疏矩阵的shape
  • sparse_value 个别元素的值
    • sparse_values是个数:所有索引指定的位置都用这个数
    • sparse_values是个向量:输出矩阵的某一行向量里某一行对应的数(所以这里向量的长度应该和输出矩阵的行数对应,不然报错)
  • default_value:未指定元素的默认值,一般如果是稀疏矩阵的话就是0了

实例展示

import tensorflow as tf  
import numpy  

BATCHSIZE=6

label=tf.expand_dims(tf.constant([0,2,3,6,7,9]),1)
index=tf.expand_dims(tf.range(0, BATCHSIZE),1)
# use a matrix
concated = tf.concat([index, label], 1)   # [[0, 0], [0, 2], [0, 3], [0, 6], [0, 7], [0, 9]] (6,2)
onehot_labels = tf.sparse_to_dense(concated, [BATCHSIZE,10], 1.0, 0.0)

# use a vector
sparse_indices2=tf.constant([1,3,4])
onehot_labels2 = tf.sparse_to_dense(sparse_indices2, [10], 1.0, 0.0)#can use

# use a scalar
sparse_indices3=tf.constant(5)
onehot_labels3 = tf.sparse_to_dense(sparse_indices3, [10], 1.0, 0.0)

sparse_tensor_00 = tf.SparseTensor(indices=[[0,0,0], [1,1,2]], values=[4, 6], dense_shape=[2,2,3])
dense_tensor_00 = tf.sparse_tensor_to_dense(sparse_tensor_00)

with tf.Session(config=config) as sess:
    result1=sess.run(onehot_labels)
    result2 = sess.run(onehot_labels2)
    result3 = sess.run(onehot_labels3)
    result4 = sess.run(dense_tensor_00)
    print ("This is result1:")
    print (result1)
    print ("This is result2:")
    print (result2)
    print ("This is result3:")
    print (result3)
    print ("This is result4:")
    print (result4)

输出结果如下

[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
This is result2:
[0. 1. 0. 1. 1. 0. 0. 0. 0. 0.]
This is result3:
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
This is result4:
[[[4 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 6]]]

区别

两者的区别可以通过应用来说起

If you would like to define the tensor outside the graph, e.g. define the sparse tensor for later data feed, use SparseTensorValue. In contrast, if the sparse tensor is defined in graph, use SparseTensor

在graph定义sparse_placeholder,在feed中需要使用SparseTensorValue

x_sp = tf.sparse_placeholder(dtype=tf.float32)
W = tf.Variable(tf.random_normal([6, 6]))
y = tf.sparse_tensor_dense_matmul(sp_a=x_sp, b=W)

init = tf.global_variables_initializer()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
sess.run(init)

stv = tf.SparseTensorValue(indices=[[0, 0], [1, 2]], values=[1.1, 1.2], 
dense_shape=[2,6])
result = sess.run(y,feed_dict={x_sp:stv})

print(result)

在graph中做定义需要使用SparseTensor

indices_i = tf.placeholder(dtype=tf.int64, shape=[2, 2])
values_i = tf.placeholder(dtype=tf.float32, shape=[2])
dense_shape_i = tf.placeholder(dtype=tf.int64, shape=[2])
st = tf.SparseTensor(indices=indices_i, values=values_i, dense_shape=dense_shape_i)

W = tf.Variable(tf.random_normal([6, 6]))
y = tf.sparse_tensor_dense_matmul(sp_a=st, b=W)

init = tf.global_variables_initializer()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
sess.run(init)

result = sess.run(y,feed_dict={indices_i:[[0, 0], [1, 2]], values_i:[1.1, 1.2], dense_shape_i:[2,6]})

print(result)

在feed中应用SparseTensor,需要使用运算

x = tf.sparse_placeholder(tf.float32)
y = tf.sparse_reduce_sum(x)

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
with tf.Session(config=config) as sess:
    indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64)
    values = np.array([1.0, 2.0], dtype=np.float32)
    shape = np.array([7, 9, 2], dtype=np.int64)

    print(sess.run(y, feed_dict={
        x: tf.SparseTensorValue(indices, values, shape)}))  # Will succeed.
    print(sess.run(y, feed_dict={
        x: (indices, values, shape)}))  # Will succeed.

    sp = tf.SparseTensor(indices=indices, values=values, dense_shape=shape)
    sp_value = sp.eval(session=sess)
    print(sp_value)
    print(sess.run(y, feed_dict={x: sp_value}))  # Will succeed.
### TensorFlow 初学者教程 TensorFlow 提供了一系列针对初学者的教程,帮助开发者快速上手深度学习框架。以下是基于官方文档和其他资源整理的内容。 #### 官方入门教程 TensorFlow 官网提供了详细的入门指南,适合新手了解如何构建简单的神经网络模型[^1]。具体来说,可以从以下链接获取完整的入门教程: - [TensorFlow Quickstart for Beginners](https://tensorflow.google.cn/tutorials/quickstart/beginner) 此教程涵盖了以下几个方面: - **环境搭建**:推荐使用 Google Colab,在线环境中已经预装了 TensorFlow 运行库[^2]。 - **数据加载与处理**:通过 MNIST 数据集演示如何准备训练和测试数据。 - **模型定义**:利用 Keras API 构建一个简单的全连接神经网络。 - **损失函数与优化器**:介绍交叉熵作为损失函数以及梯度下降法的应用。 - **评估与预测**:展示如何计算模型精度并对新样本做出分类预测。 #### 示例代码解析 下面是一个典型的 TensorFlow 初学实例,用于解决 MNIST 手写数字识别问题: ```python import tensorflow as tf # 加载MNIST数据集 mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # 归一化图像数据到[0, 1]范围 x_train, x_test = x_train / 255.0, x_test / 255.0 # 构建顺序模型 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), # 将二维数组展平为一维向量 tf.keras.layers.Dense(128, activation='relu'), # 隐藏层,激活函数ReLU tf.keras.layers.Dropout(0.2), # Dropout防止过拟合 tf.keras.layers.Dense(10, activation='softmax') # 输出层,Softmax多分类 ]) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', # 使用稀疏交叉熵损失函数 metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, epochs=5) # 测试模型性能 test_loss, test_acc = model.evaluate(x_test, y_test) print(f'Test accuracy: {test_acc}') ``` 上述代码展示了如何使用 TensorFlow 和 Keras 创建一个多层感知机(MLP),并通过 Adam 优化算法调整权重来最小化误差。 #### 常见错误提示及其解决方案 对于提到的 `input_data` 错误情况,这是因为较新的版本中移除了对该模块的支持。建议改用内置方法下载并读取 MNIST 数据集合[^3]。另外需要注意的是,不同版本间可能存在接口差异,请确认所依赖的具体版次是否匹配当前开发需求[^4]。 #### 关于 MNIST 数据结构说明 每张图片尺寸均为 \(28 \times 28\) 像素点阵形式呈现灰阶影像资料;经过转换后成为长度等于784的一维特征向量输入至网络之中参与运算过程。而目标输出则由十个独立节点构成的概率分布矢量表示各类别可能性大小关系[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

callinglove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值