拼接数组/删除元素

2024-09-06 03:32
文章标签 数组 元素 删除 拼接

本文主要是介绍拼接数组/删除元素,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

矩阵拼接的函数tf.stack()与矩阵分解的函数tf.unstack()

tf.unstack(value, num=None, axis=0, name='unstack')Unpacks the given dimension of a rank-`R` tensor into rank-`(R-1)` tensors.Unpacks `num` tensors from `value` by chipping it along the `axis` dimension.    Args:
      value: A rank `R > 0` `Tensor` to be unstacked.
      num: An `int`. The length of the dimension `axis`. Automatically inferred//一个“int”。尺寸“轴”的长度。自动推断为“无”(默认)。if `None` (the default).
      axis: An `int`. The axis to unstack along. Defaults to the firstdimension. Supports negative indexes.
      name: A name for the operation (optional).    Returns:The list of `Tensor` objects unstacked from `value`.    Raises:
      ValueError: If `num` is unspecified and cannot be inferred.
      ValueError: If `axis` is out of the range [-R, R).
import tensorflow as tf
a = tf.constant([1,2,3])
b = tf.constant([4,5,6])
c = tf.stack([a,b],axis=1)
d = tf.unstack(c,axis=0)
e = tf.unstack(c,axis=1)
print(c.get_shape())
with tf.Session() as sess:print(sess.run(c))print(sess.run(d))print(sess.run(e))(3, 2)[[1 4] 
[2 5] 
[3 6]][array([1, 4]), array([2, 5]), array([3, 6])][array([1, 2, 3]), array([4, 5, 6])]

numpy.delete删除行或列

import numpy as np
A = np.delete(B, 2, axis=0)  # 删除B的第三行
B = np.delete(C, 1, axis=1)  # 删除C的第2列
  • 删除一列
>>> dataset=[[1,2,3],[2,3,4],[4,5,6]]  
>>> import numpy as np  
>>> dataset = np.delete(dataset, -1, axis=1)  
>>> dataset  
array([[1, 2],  [2, 3],  [4, 5]])  
  • 删除多列
arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])  
np.delete(arr, [1,2], axis=1)  
array([[ 1,  4],  [ 5,  8],  [ 9, 12]])  

拼接_numpy列表索引方式

a=np.array([[1,2],[3,4],[5,6],[7,8]])
b=a[:2]
  • numpy.concatenate
    numpy.concatenate((a1, a2, …), axis=0)
    Join a sequence of arrays along an existing axis.
    Parameters:
    a1, a2, … : sequence of array_like
    The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
    axis : int, optional
    The axis along which the arrays will be joined. Default is 0.
    Returns:
    res : ndarray
    The concatenated array.
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],[3, 4],[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],[3, 4, 6]])
###############################
>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data = [0 -- 2],mask = [False  True False],fill_value = 999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data = [0 1 2 2 3 4],mask = False,fill_value = 999999)
>>> np.ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],mask = [False  True False False False False],fill_value = 999999)

拼接_tf.concat

这里写图片描述

    pythont1 = [[1, 2, 3], [4, 5, 6]]t2 = [[7, 8, 9], [10, 11, 12]]tf.concat([t1, t2], 0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]tf.concat([t1, t2], 1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]# tensor t3 with shape [2, 3]# tensor t4 with shape [2, 3]tf.shape(tf.concat([t3, t4], 0)) ==> [4, 3]tf.shape(tf.concat([t3, t4], 1)) ==> [2, 6]

拼接_keras.legacy.layers.merge

Help on function merge in module keras.legacy.layers:merge(inputs, mode='sum', concat_axis=-1, dot_axes=-1, output_shape=None, output_mask=None, arguments=None, name=None)Functional merge, to apply to Keras tensors (NOT layers).Returns a Keras tensor.# Example# Argumentsmode: String or lambda/function. If string, must be oneof: 'sum', 'mul', 'concat', 'ave', 'cos', 'dot', 'max'.If lambda/function, it should take as input a list of tensorsand return a single tensor.concat_axis: Integer, axis to use in mode `concat`.dot_axes: Integer or tuple of integers,axes to use in mode `dot` or `cos`.output_shape: Shape tuple (tuple of integers), or lambda/functionto compute output_shape (only if merge mode is a lambda/function).If the latter case, it should take as input a list of shape tuples(1:1 mapping to input tensors) and return a single shape tuple,including the batch size(same convention as the `compute_output_shape` method of layers).node_indices: Optional list of integers containingthe output node index for each input layer(in case some input layers have multiple output nodes).will default to an array of 0s if not provided.tensor_indices: Optional list of indices of output tensorsto consider for merging(in case some input layer node returns multiple tensors).
concat_feat = merge([concat_feat, x], mode='concat', concat_axis=concat_axis, name='concat_'+str(stage)+'_'+str(branch))

拼接_keras.legacy.layers.merge.concatenate()

>>> import keras.legacy.layers as layers
>>> dir(layers)
['AtrousConvolution1D', 'AtrousConvolution2D', 'Highway', 'InputSpec', 'K', 'Layer', 'MaxoutDense', 'Merge', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'activations', 'constraints', 'func_dump', 'func_load', 'initializers', 'inspect', 'merge', 'python_types', 'regularizers', 'warnings']
>>>
>>> dir(layers.Merge)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add_inbound_node', '_arguments_validation', '_get_node_attribute_at_index', 'add_loss', 'add_update', 'add_weight', 'assert_input_compatibility', 'build', 'built', 'call', 'compute_mask', 'compute_output_shape', 'constraints', 'count_params', 'from_config', 'get_config', 'get_input_at', 'get_input_mask_at', 'get_input_shape_at', 'get_losses_for', 'get_output_at', 'get_output_mask_at', 'get_output_shape_at', 'get_updates_for', 'get_weights', 'input', 'input_mask', 'input_shape', 'losses', 'non_trainable_weights', 'output', 'output_mask', 'output_shape', 'set_weights', 'trainable_weights', 'updates', 'weights']
def concatenate(inputs, axis=-1, **kwargs):"""Functional interface to the `Concatenate` layer.# Argumentsinputs: A list of input tensors (at least 2).axis: Concatenation axis.**kwargs: Standard layer keyword arguments.# ReturnsA tensor, the concatenation of the inputs alongside axis `axis`."""return Concatenate(axis=axis, **kwargs)(inputs)
x = layers.concatenate([branch1x1, branch5x5, branch3x3dbl, branch_pool],axis=channel_axis,name='mixed1')

mxnet.ndarray.concat(*data, **kwargs)

这里写图片描述

x = [[1,1],[2,2]]
y = [[3,3],[4,4],[5,5]]
z = [[6,6], [7,7],[8,8]]concat(x,y,z,dim=0) = [[ 1.,  1.],[ 2.,  2.],[ 3.,  3.],[ 4.,  4.],[ 5.,  5.],[ 6.,  6.],[ 7.,  7.],[ 8.,  8.]]Note that you cannot concat x,y,z along dimension 1 since dimension
0 is not the same for all the input arrays.concat(y,z,dim=1) = [[ 3.,  3.,  6.,  6.],[ 4.,  4.,  7.,  7.],[ 5.,  5.,  8.,  8.]]
print('real...')
test_iter.reset()
batch = test_iter.next()
y_te = batch.label[0]
# print(batch.label[0], batch.data[0].shape)for batch in test_iter:y_te = mx.ndarray.concat(y_te, batch.label[0], dim=0)
print(len(batch.label[0]), len(y_te))
mxnet.symbol.Concat(*data, **kwargs)
Parameters: 
data (Symbol[]) – List of arrays to concatenate
dim (int, optional, default='1') – the dimension to be concated.
name (string, optional.) – Name of the resulting symbol.
Returns:    
The result symbol.Return type:    
SymbolExamplesConcat two (or more) inputs along a specific dimension:>>> a = Variable('a')
>>> b = Variable('b')
>>> c = Concat(a, b, dim=1, name='my-concat')
>>> c>>> SymbolDoc.get_output_shape(c, a=(128, 10, 3, 3), b=(128, 15, 3, 3))
{'my-concat_output': (128L, 25L, 3L, 3L)}
mxnet.symbol.slice_axis(data=None, axis=_Null, begin=_Null, end=_Null, name=None, attr=None, out=None, **kwargs)
Parameters: 
data (Symbol) – Source input
axis (int, required) – Axis along which to be sliced, supports negative indexes.
begin (int, required) – The beginning index along the axis to be sliced, supports negative indexes.
end (int or None, required) – The ending index along the axis to be sliced, supports negative indexes.
name (string, optional.) – Name of the resulting symbol.
Returns:    
The result symbol.Return type:Examples:x = [[  1.,   2.,   3.,   4.],[  5.,   6.,   7.,   8.],[  9.,  10.,  11.,  12.]]slice_axis(x, axis=0, begin=1, end=3) = [[  5.,   6.,   7.,   8.],[  9.,  10.,  11.,  12.]]slice_axis(x, axis=1, begin=0, end=2) = [[  1.,   2.],[  5.,   6.],[  9.,  10.]]slice_axis(x, axis=1, begin=-3, end=-1) = [[  2.,   3.],[  6.,   7.],[ 10.,  11.]]

这篇关于拼接数组/删除元素的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1140877

相关文章

redis过期key的删除策略介绍

《redis过期key的删除策略介绍》:本文主要介绍redis过期key的删除策略,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录第一种策略:被动删除第二种策略:定期删除第三种策略:强制删除关于big key的清理UNLINK命令FLUSHALL/FLUSHDB命

Java数组初始化的五种方式

《Java数组初始化的五种方式》数组是Java中最基础且常用的数据结构之一,其初始化方式多样且各具特点,本文详细讲解Java数组初始化的五种方式,分析其适用场景、优劣势对比及注意事项,帮助避免常见陷阱... 目录1. 静态初始化:简洁但固定代码示例核心特点适用场景注意事项2. 动态初始化:灵活但需手动管理代

C++中初始化二维数组的几种常见方法

《C++中初始化二维数组的几种常见方法》本文详细介绍了在C++中初始化二维数组的不同方式,包括静态初始化、循环、全部为零、部分初始化、std::array和std::vector,以及std::vec... 目录1. 静态初始化2. 使用循环初始化3. 全部初始化为零4. 部分初始化5. 使用 std::a

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

如何高效移除C++关联容器中的元素

《如何高效移除C++关联容器中的元素》关联容器和顺序容器有着很大不同,关联容器中的元素是按照关键字来保存和访问的,而顺序容器中的元素是按它们在容器中的位置来顺序保存和访问的,本文介绍了如何高效移除C+... 目录一、简介二、移除给定位置的元素三、移除与特定键值等价的元素四、移除满足特android定条件的元

MySQL更新某个字段拼接固定字符串的实现

《MySQL更新某个字段拼接固定字符串的实现》在MySQL中,我们经常需要对数据库中的某个字段进行更新操作,本文就来介绍一下MySQL更新某个字段拼接固定字符串的实现,感兴趣的可以了解一下... 目录1. 查看字段当前值2. 更新字段拼接固定字符串3. 验证更新结果mysql更新某个字段拼接固定字符串 -

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

macOS无效Launchpad图标轻松删除的4 种实用方法

《macOS无效Launchpad图标轻松删除的4种实用方法》mac中不在appstore上下载的应用经常在删除后它的图标还残留在launchpad中,并且长按图标也不会出现删除符号,下面解决这个问... 在 MACOS 上,Launchpad(也就是「启动台」)是一个便捷的 App 启动工具。但有时候,应

Mysql删除几亿条数据表中的部分数据的方法实现

《Mysql删除几亿条数据表中的部分数据的方法实现》在MySQL中删除一个大表中的数据时,需要特别注意操作的性能和对系统的影响,本文主要介绍了Mysql删除几亿条数据表中的部分数据的方法实现,具有一定... 目录1、需求2、方案1. 使用 DELETE 语句分批删除2. 使用 INPLACE ALTER T

python中字符串拼接的几种方法及优缺点对比详解

《python中字符串拼接的几种方法及优缺点对比详解》在Python中,字符串拼接是常见的操作,Python提供了多种方法来拼接字符串,每种方法有其优缺点和适用场景,以下是几种常见的字符串拼接方法,需... 目录1. 使用 + 运算符示例:优缺点:2. 使用&nbsjsp;join() 方法示例:优缺点:3