pytorch和tensorflow2中的模块函数名称记录(混个脸熟)

一、背景

听说AI很多开源框架,有个师兄说pytorch和tensorflow是必会的。所以今天一起了解下。两脚走路,两手都要抓,两手都要硬。

二、软件安装和使用查看

安装pytorch,看官网;
在这里插入图片描述
安装tensorflow。

(torch_tensorflow_venv) root@h:~/hom_zdl# pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
(torch_tensorflow_venv) root@h:~/hom_zdl# pip install tensorflow

在这里插入图片描述
安装完成。

2.1 pytorch所有功能函数

(有剔除一些“_“开头的内置函数)

>>> import torch
>>> import torch.nn as nn
>>> torch_functions = sorted(dir(torch))
>>> nn_functions = sorted(dir(nn))
>>> print("torch functions: ", torch_functions)
torch functions:  ['AVG', 'AggregationType', 'AliasDb', 'Any', 'AnyType', 'Argument', 'ArgumentSpec', 'AwaitType', 
'BFloat16Storage', 'BFloat16Tensor', 'BenchmarkConfig', 'BenchmarkExecutionStats', 'Block', 'BoolStorage', 'BoolTensor',
 'BoolType', 'BufferDict', 'ByteStorage', 'ByteTensor', 'CallStack', 'Callable', 'Capsule', 'CharStorage', 'CharTensor', 
 'ClassType', 'Code', 'CompilationUnit', 'CompleteArgumentSpec', 'ComplexDoubleStorage', 'ComplexFloatStorage', 'ComplexType', 
 'ConcreteModuleType', 'ConcreteModuleTypeBuilder', 'DeepCopyMemoTable', 'DeserializationStorageContext', 
 'DeviceObjType', 'Dict', 'DictType', 'DisableTorchFunction', 
 'DisableTorchFunctionSubclass', 'DispatchKey', 'DispatchKeySet',
  'DoubleStorage', 'DoubleTensor', 'EnumType', 'ErrorReport', 'ExcludeDispatchKeyGuard', 'ExecutionPlan', 'FatalError', 
  'FileCheck', 'FloatStorage', 'FloatTensor', 'FloatType', 'FunctionSchema', 'Future', 'FutureType', 'Generator', 'Gradient', 
  'Graph', 'GraphExecutorState', 'HalfStorage', 'HalfTensor', 'IODescriptor', 'InferredType', 'IntStorage', 'IntTensor', 'IntType', 'InterfaceType', 'JITException', 'List', 'ListType', 
  'LiteScriptModule', 'LockingLogger', 'LoggerBase', 'LongStorage', 'LongTensor', 'ModuleDict', 'Node', 'NoneType', 'NoopLogger', 
  'NumberType', 'OperatorInfo', 'Optional', 'OptionalType', 'PRIVATE_OPS', 'ParameterDict', 'PyObjectType', 
  'PyTorchFileReader', 'PyTorchFileWriter', 'QInt32Storage', 
  'QInt8Storage', 'QUInt2x4Storage', 'QUInt4x2Storage', 'QUInt8Storage', 'RRefType', 'SUM', 'ScriptClass', 
  'ScriptClassFunction', 'ScriptDict', 'ScriptDictIterator', 'ScriptDictKeyIterator', 'ScriptFunction', 'ScriptList', 'ScriptListIterator', 'ScriptMethod', 'ScriptModule', 
  'ScriptModuleSerializer', 'ScriptObject', 'ScriptObjectProperty', 'SerializationStorageContext', 'Set', 'ShortStorage', 
  'ShortTensor', 'Size', 'StaticModule', 'Storage', 'StorageBase', 'Stream', 'StreamObjType', 'StringType', 'SymBool', 'SymBoolType', 
  'SymFloat', 'SymInt', 'SymIntType', 'TYPE_CHECKING', 'Tag', 
  'Tensor', 'TensorType', 'ThroughputBenchmark', 'TracingState', 'Tuple', 'TupleType', 'Type', 'TypedStorage', 'USE_GLOBAL_DEPS', 'USE_RTLD_GLOBAL_WITH_LIBTORCH', 'Union', 'UnionType', 
  'UntypedStorage', 'Use', 'Value', 
  'abs', 'abs_', 'absolute', 'acos', 'acos_', 'acosh', 'acosh_', 'adaptive_avg_pool1d', 'adaptive_max_pool1d', 'add', 'addbmm', 
  'addcdiv', 'addcmul', 'addmm', 'addmv', 'addmv_', 'addr', 
  'adjoint', 'affine_grid_generator', 'alias_copy', 'align_tensors', 'all', 'allclose', 'alpha_dropout', 
  'alpha_dropout_', 'amax', 'amin', 'aminmax', 'amp', 'angle', 'any', 'ao', 'arange', 'arccos', 'arccos_', 'arccosh', 'arccosh_', 'arcsin', 'arcsin_', 'arcsinh', 'arcsinh_', 'arctan', 'arctan2', 
  'arctan_', 'arctanh', 'arctanh_', 
  'are_deterministic_algorithms_enabled', 'argmax', 'argmin', 'argsort', 'argwhere', 'as_strided', 'as_strided_', 
  'as_strided_copy', 'as_strided_scatter', 'as_tensor', 'asarray', 'asin', 'asin_', 'asinh', 'asinh_', 'atan', 'atan2', 'atan_', 
  'atanh', 'atanh_', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'attr', 'autocast', 'autocast_decrement_nesting', 
  'autocast_increment_nesting', 'autograd', 'avg_pool1d', 'backends', 'baddbmm', 'bartlett_window', 'base_py_dll_path', 'batch_norm', 'batch_norm_backward_elemt', 
  'batch_norm_backward_reduce', 'batch_norm_elemt', 'batch_norm_gather_stats', 'batch_norm_gather_stats_with_counts', 'batch_norm_stats', 'batch_norm_update_stats', 'bernoulli', 
  'bfloat16', 'bilinear', 'binary_cross_entropy_with_logits', 'bincount', 'binomial', 'bits16', 'bits1x8', 'bits2x4', 'bits4x2', 'bits8', 'bitwise_and', 'bitwise_left_shift', 'bitwise_not', 
  'bitwise_or', 'bitwise_right_shift', 'bitwise_xor', 'blackman_window', 'block_diag', 'bmm', 'bool', 'broadcast_shapes', 'broadcast_tensors', 'broadcast_to', 'bucketize', 'builtins', 
  'can_cast', 'candidate', 'cartesian_prod', 'cat', 
  'ccol_indices_copy', 'cdist', 'cdouble', 'ceil', 'ceil_', 'celu', 'celu_', 'cfloat', 'chain_matmul', 'chalf', 'channel_shuffle', 'channels_last', 'channels_last_3d', 'cholesky', 
  'cholesky_inverse', 'cholesky_solve', 'choose_qparams_optimized', 'chunk', 'clamp', 'clamp_', 'clamp_max', 'clamp_max_', 'clamp_min', 'clamp_min_', 'classes', 'classproperty', 'clear_autocast_cache',
'clip', 'clip_', 'clone', 'col_indices_copy', 'column_stack', 
'combinations', 'compile', 'compiled_with_cxx11_abi', 'compiler', 'complex', 'complex128', 'complex32', 'complex64', 'concat', 
'concatenate', 'cond', 'conj', 'conj_physical', 'conj_physical_', 'constant_pad_nd', 'contiguous_format', 'conv1d', 'conv2d', 
'conv3d', 'conv_tbc', 'conv_transpose1d', 'conv_transpose2d', 
  'conv_transpose3d', 'convolution', 'copysign', 'corrcoef', 'cos', 'cos_', 'cosh', 'cosh_', 'cosine_embedding_loss', 
  'cosine_similarity', 'count_nonzero', 'cov', 'cpp', 'cpu', 'cross', 'crow_indices_copy', 'ctc_loss', 'ctypes', 'cuda', 
  'cuda_path', 'cuda_version', 'cudnn_affine_grid_generator', 'cudnn_batch_norm', 'cudnn_convolution', 
  'cudnn_convolution_add_relu', 'cudnn_convolution_relu', 'cudnn_convolution_transpose', 'cudnn_grid_sampler', 
  'cudnn_is_acceptable', 'cummax', 'cummin', 'cumprod', 'cumsum', 'cumulative_trapezoid', 'default_generator', 'deg2rad', 'deg2rad_', 
'dequantize', 'det', 'detach', 'detach_', 'detach_copy', 
'device', 'diag', 'diag_embed', 'diagflat', 'diagonal', 'diagonal_copy', 
  'diagonal_scatter', 'diff', 'digamma', 'dist', 'distributed', 'distributions', 'div', 'divide', 'dll', 'dll_path', 'dll_paths',
'dlls', 'dot', 'double', 'dropout', 'dropout_', 'dsmm', 'dsplit',
'dstack', 'dtype', 'e', 'eig', 'einsum', 'embedding', 
  'embedding_bag', 'embedding_renorm_', 'empty', 'empty_like', 'empty_permuted', 'empty_quantized', 'empty_strided', 
  'enable_grad', 'eq', 'equal', 'erf', 'erf_', 'erfc', 'erfc_', 'erfinv', 'exp', 'exp2', 'exp2_', 'exp_', 'expand_copy', 'expm1', 'expm1_', 'export', 'eye', 'fake_quantize_per_channel_affine', 
  'fake_quantize_per_tensor_affine', 'fbgemm_linear_fp16_weight', 'fbgemm_linear_fp16_weight_fp32_activation', 
  'fbgemm_linear_int8_weight', 'fbgemm_linear_int8_weight_fp32_activation', 
  'fbgemm_linear_quantize_weight', 'fbgemm_pack_gemm_matrix_fp16', 'fbgemm_pack_quantized_matrix', 'feature_alpha_dropout', 
  'feature_alpha_dropout_', 'feature_dropout', 'feature_dropout_', 'fft', 'fill', 'fill_', 'finfo', 'fix', 'fix_', 'flatten', 'flip', 'fliplr', 'flipud',
 'float', 'float16', 'float32', 'float64', 'float8_e4m3fn', 'float8_e4m3fnuz', 'float8_e5m2', 
  'float8_e5m2fnuz', 'float_power', 'floor', 'floor_', 
  'floor_divide', 'fmax', 'fmin', 'fmod', 'fork', 'frac', 'frac_', 'frexp', 'frobenius_norm', 'from_dlpack', 'from_file', 
  'from_numpy', 'frombuffer', 'full', 'full_like', 'func', 'functional', 'fused_moving_avg_obs_fake_quant', 'futures', 'fx', 'gather', 'gcd', 'gcd_', 'ge', 'geqrf', 'ger', 
  'get_autocast_cpu_dtype', 'get_autocast_gpu_dtype', 'get_autocast_ipu_dtype', 'get_autocast_xla_dtype', 
  'get_default_dtype', 'get_deterministic_debug_mode', 'get_device', 'get_file_path', 'get_float32_matmul_precision', 'get_num_interop_threads', 'get_num_threads', 'get_rng_state',
   'glob', 'gradient', 'greater', 'greater_equal', 'grid_sampler', 'grid_sampler_2d', 'grid_sampler_3d', 'group_norm', 'gru', 'gru_cell', 'gt', 'half', 'hamming_window', 'hann_window', 
   'hardshrink', 'has_lapack', 'has_mkl', 'has_openmp', 
   'has_spectral', 'heaviside', 'hinge_embedding_loss', 'histc', 'histogram', 'histogramdd', 'hsmm', 'hsplit', 'hspmm', 'hstack', 'hub', 'hypot', 'i0', 'i0_', 'igamma', 'igammac', 'iinfo', 'imag',
'import_ir_module', 'import_ir_module_from_buffer', 'index_add', 'index_copy', 'index_fill', 'index_put', 'index_put_', 
'index_reduce', 'index_select', 'indices_copy', 'inf', 
'inference_mode', 'init_num_threads', 'initial_seed', 'inner', 'inspect', 'instance_norm', 'int', 'int16', 'int32', 'int64',
'int8', 'int_repr', 'inverse', 'is_anomaly_check_nan_enabled', 
'is_anomaly_enabled', 'is_autocast_cache_enabled', 
   'is_autocast_cpu_enabled', 'is_autocast_enabled', 
   'is_autocast_ipu_enabled', 'is_autocast_xla_enabled', 'is_complex', 'is_conj', 'is_deterministic_algorithms_warn_only_enabled', 'is_distributed', 'is_floating_point', 'is_grad_enabled',
'is_inference', 
'is_inference_mode_enabled', 'is_loaded', 'is_neg', 'is_nonzero', 'is_same_size', 'is_signed', 'is_storage', 'is_tensor', 'is_vulkan_available', 'is_warn_always_enabled',
    'isclose', 'isfinite', 'isin', 'isinf', 'isnan', 'isneginf', 'isposinf', 'isreal', 'istft', 'jagged', 'jit', 'kaiser_window', 'kernel32', 'kl_div', 'kron', 'kthvalue', 'last_error', 
    'layer_norm', 'layout', 'lcm', 'lcm_', 'ldexp', 'ldexp_', 'le', 'legacy_contiguous_format', 'lerp', 'less', 'less_equal', 'lgamma', 'library', 'linalg', 'linspace', 'load', 'lobpcg',
'log', 'log10', 'log10_', 'log1p', 'log1p_', 'log2', 'log2_', 'log_', 
    'log_softmax', 'logaddexp', 'logaddexp2', 'logcumsumexp', 'logdet', 'logical_and', 'logical_not', 'logical_or', 
    'logical_xor', 'logit', 'logit_', 'logspace', 'logsumexp', 'long', 'lstm', 'lstm_cell', 'lstsq', 'lt', 'lu', 'lu_solve', 
'lu_unpack', 'manual_seed', 'margin_ranking_loss', 'masked', 'masked_fill', 'masked_scatter', 'masked_select', 'math', 'matmul',
'matrix_exp', 'matrix_power', 'matrix_rank', 'max', 'max_pool1d', 
'max_pool1d_with_indices', 'max_pool2d', 'max_pool3d', 'maximum', 'mean', 'median', 'memory_format', 'merge_type_from_type_comment', 'meshgrid', 'min', 'minimum', 'miopen_batch_norm', 
    'miopen_convolution', 'miopen_convolution_add_relu', 'miopen_convolution_relu', 'miopen_convolution_transpose', 'miopen_depthwise_convolution', 'miopen_rnn',
'mkldnn_adaptive_avg_pool2d', 'mkldnn_convolution', 
'mkldnn_linear_backward_weights', 'mkldnn_max_pool2d', 
'mkldnn_max_pool3d', 'mkldnn_rnn_layer', 'mm', 'mode', 'moveaxis', 'movedim', 'mps', 'msort', 'mul', 'multinomial', 'multiply', 'multiprocessing', 'mv', 'mvlgamma', 'name', 'nan', 'nan_to_num', 
'nan_to_num_', 'nanmean', 'nanmedian', 'nanquantile', 'nansum', 'narrow', 'narrow_copy', 'native_batch_norm', 
    'native_channel_shuffle', 'native_dropout', 'native_group_norm', 'native_layer_norm', 'native_norm', 'ne', 
    'neg', 'neg_', 'negative', 'negative_', 'nested', 'nextafter', 'nn', 'no_grad', 'nonzero', 'nonzero_static', 'norm', 
    'norm_except_dim', 'normal', 'not_equal', 'nuclear_norm', 
    'numel', 'nvtoolsext_dll_path', 'obj', 'ones', 'ones_like', 'ops', 'optim', 'orgqr', 'ormqr', 'os', 'outer', 'overrides', 'package', 'pairwise_distance', 'parse_ir', 'parse_schema', 
'parse_type_comment', 'path_patched', 'pca_lowrank', 'pdist', 'per_channel_affine', 'per_channel_affine_float_qparams', 
'per_channel_symmetric', 'per_tensor_affine', 'per_tensor_symmetric', 'permute', 'permute_copy', 'pfiles_path', 'pi', 'pinverse', 'pixel_shuffle', 'pixel_unshuffle', 'platform',
     'poisson', 'poisson_nll_loss', 'polar', 'polygamma', 'positive', 'pow', 'prelu', 'prepare_multiprocessing_environment',
      'preserve_format', 'prev_error_mode', 'prod', 'profiler', 'promote_types', 'put', 'py_dll_path', 'py_float', 'py_int', 
      'q_per_channel_axis', 'q_per_channel_scales', 
      'q_per_channel_zero_points', 'q_scale', 'q_zero_point', 'qint32', 'qint8', 'qr', 'qscheme', 'quantile', 'quantization', 'quantize_per_channel', 'quantize_per_tensor', 
'quantize_per_tensor_dynamic', 'quantized_batch_norm', 
'quantized_gru', 'quantized_gru_cell', 'quantized_lstm',
'quantized_lstm_cell', 'quantized_max_pool1d', 'quantized_max_pool2d', 'quantized_max_pool3d', 
'quantized_rnn_relu_cell', 'quantized_rnn_tanh_cell',
'quasirandom', 'quint2x4', 'quint4x2', 'quint8', 'rad2deg', 'rad2deg_', 'rand', 'rand_like', 'randint', 'randint_like', 'randn', 'randn_like', 'random', 'randperm', 'range', 'ravel',
'read_vitals', 'real', 'reciprocal', 'reciprocal_', 'relu', 'relu_', 'remainder', 'renorm', 'repeat_interleave', 'res', 'reshape', 'resize_as_', 'resize_as_sparse_', 'resolve_conj', 
'resolve_neg', 'result_type', 'return_types', 'rnn_relu', 'rnn_relu_cell', 'rnn_tanh', 'rnn_tanh_cell', 'roll', 'rot90', 
'round', 'round_', 'row_indices_copy', 'row_stack', 'rrelu', 'rrelu_', 'rsqrt', 'rsqrt_', 'rsub', 'saddmm', 'save', 'scalar_tensor', 'scatter', 'scatter_add', 'scatter_reduce',
'searchsorted', 'seed', 'segment_reduce', 'select', 'select_copy', 'select_scatter', 'selu', 'selu_', 'serialization', 
'set_anomaly_enabled', 'set_autocast_cache_enabled', 
'set_autocast_cpu_dtype', 'set_autocast_cpu_enabled', 
'set_autocast_enabled', 'set_autocast_gpu_dtype', 'set_autocast_ipu_dtype', 'set_autocast_ipu_enabled', 'set_autocast_xla_dtype', 'set_autocast_xla_enabled', 
'set_default_device', 'set_default_dtype', 
'set_default_tensor_type', 'set_deterministic_debug_mode', 'set_float32_matmul_precision', 'set_flush_denormal',
'set_grad_enabled', 'set_num_interop_threads', 'set_num_threads', 'set_printoptions', 'set_rng_state', 
'set_vital', 'set_warn_always', 'sgn', 'short', 'sigmoid', 'sigmoid_', 'sign', 'signal', 'signbit', 'sin', 'sin_', 'sinc', 'sinc_', 'sinh', 'sinh_', 'slice_copy', 'slice_scatter', 'slogdet',
'smm', 'softmax', 'solve', 'sort', 'sparse', 'sparse_bsc', 
'sparse_bsc_tensor', 'sparse_bsr', 'sparse_bsr_tensor', 'sparse_compressed_tensor', 'sparse_coo', 'sparse_coo_tensor', 
'sparse_csc', 'sparse_csc_tensor', 'sparse_csr', 'sparse_csr_tensor', 'special', 'split', 'split_copy', 
'split_with_sizes', 'split_with_sizes_copy', 'spmm', 'sqrt', 'sqrt_', 'square', 'square_', 'squeeze', 'squeeze_copy', 'sspaddmm', 'stack', 'std', 'std_mean', 'stft', 'storage', 
'strided', 'sub', 'subtract', 'sum', 'svd', 'svd_lowrank', 'swapaxes', 'swapdims', 'sym_constrain_range', 'sym_constrain_range_for_size', 'sym_float', 'sym_int', 'sym_ite',
'sym_max', 'sym_min', 'sym_not', 'sym_sqrt', 'symeig', 'sys', 't', 't_copy', 'take', 'take_along_dim', 'tan', 'tan_', 'tanh',
'tanh_', 'tensor', 'tensor_split', 'tensordot', 'testing', 'textwrap', 
'th_dll_path', 'threshold', 'threshold_', 'tile', 'to_dlpack', 'topk', 'torch', 'torch_version', 'trace', 'transpose', 'transpose_copy', 'trapezoid', 'trapz', 
'triangular_solve', 'tril', 'tril_indices', 'triplet_margin_loss', 'triu', 'triu_indices', 'true_divide', 'trunc', 'trunc_', 'typename', 'types', 'uint8', 'unbind', 
'unbind_copy', 'unflatten', 'unfold_copy', 'unify_type_list', 'unique', 'unique_consecutive', 'unravel_index', 'unsafe_chunk', 'unsafe_split', 'unsafe_split_with_sizes', 
'unsqueeze', 'unsqueeze_copy', 'use_deterministic_algorithms', 'utils', 'values_copy', 'vander', 'var', 'var_mean', 'vdot', 'version', 'view_as_complex', 
'view_as_complex_copy', 'view_as_real', 'view_as_real_copy', 'view_copy', 'vitals_enabled', 'vmap', 'vsplit', 'vstack', 'wait', 'where', 'windows', 
'with_load_library_flags', 'xlogy', 'xlogy_', 'zero_', 'zeros', 'zeros_like']
>>> print("nn functions:", nn_functions)
nn functions: ['AdaptiveAvgPool1d', 'AdaptiveAvgPool2d', 'AdaptiveAvgPool3d', 'AdaptiveLogSoftmaxWithLoss', 
'AdaptiveMaxPool1d', 'AdaptiveMaxPool2d', 'AdaptiveMaxPool3d', 'AlphaDropout', 'AvgPool1d', 'AvgPool2d', 'AvgPool3d', 'BCELoss', 
'BCEWithLogitsLoss', 'BatchNorm1d', 'BatchNorm2d', 'BatchNorm3d', 'Bilinear', 'CELU', 'CTCLoss', 'ChannelShuffle', 'CircularPad1d', 
'CircularPad2d', 'CircularPad3d', 'ConstantPad1d', 'ConstantPad2d', 'ConstantPad3d', 'Container', 'Conv1d', 'Conv2d', 'Conv3d', 
'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d', 'CosineEmbeddingLoss', 'CosineSimilarity', 'CrossEntropyLoss', 'CrossMapLRN2d', 'DataParallel', 'Dropout', 'Dropout1d', 
'Dropout2d', 'Dropout3d', 'ELU', 'Embedding', 'EmbeddingBag', 'FeatureAlphaDropout', 'Flatten', 'Fold', 'FractionalMaxPool2d', 
'FractionalMaxPool3d', 'GELU', 'GLU', 'GRU', 'GRUCell', 'GaussianNLLLoss', 'GroupNorm', 'Hardshrink', 'Hardsigmoid', 
'Hardswish', 'Hardtanh', 'HingeEmbeddingLoss', 'HuberLoss', 
'Identity', 'InstanceNorm1d', 'InstanceNorm2d', 'InstanceNorm3d', 'KLDivLoss', 'L1Loss', 'LPPool1d', 'LPPool2d',
 'LSTM', 'LSTMCell', 'LayerNorm', 'LazyBatchNorm1d', 'LazyBatchNorm2d', 
'LazyBatchNorm3d', 'LazyConv1d', 'LazyConv2d', 'LazyConv3d', 'LazyConvTranspose1d', 'LazyConvTranspose2d', 
'LazyConvTranspose3d', 'LazyInstanceNorm1d', 'LazyInstanceNorm2d', 'LazyInstanceNorm3d', 'LazyLinear', 'LeakyReLU', 'Linear', 
'LocalResponseNorm', 'LogSigmoid', 'LogSoftmax', 'MSELoss', 'MarginRankingLoss', 'MaxPool1d', 'MaxPool2d', 'MaxPool3d', 
'MaxUnpool1d', 'MaxUnpool2d', 'MaxUnpool3d', 'Mish', 'Module', 'ModuleDict', 'ModuleList', 'MultiLabelMarginLoss', 
'MultiLabelSoftMarginLoss', 'MultiMarginLoss', 'MultiheadAttention', 'NLLLoss', 'NLLLoss2d', 'PReLU', 
'PairwiseDistance', 'Parameter', 'ParameterDict', 'ParameterList', 'PixelShuffle', 'PixelUnshuffle', 'PoissonNLLLoss', 'RNN', 
'RNNBase', 'RNNCell', 'RNNCellBase', 'RReLU', 'ReLU', 'ReLU6', 'ReflectionPad1d', 'ReflectionPad2d', 'ReflectionPad3d', 'ReplicationPad1d', 'ReplicationPad2d', 'ReplicationPad3d', 'SELU', 
'Sequential', 'SiLU', 'Sigmoid', 'SmoothL1Loss', 'SoftMarginLoss', 'Softmax', 'Softmax2d', 'Softmin', 'Softplus', 'Softshrink', 'Softsign', 'SyncBatchNorm', 'Tanh', 'Tanhshrink', 'Threshold', 
'Transformer', 'TransformerDecoder', 'TransformerDecoderLayer', 'TransformerEncoder', 'TransformerEncoderLayer', 
'TripletMarginLoss', 'TripletMarginWithDistanceLoss', 'Unflatten', 'Unfold', 'UninitializedBuffer', 'UninitializedParameter', 
'Upsample', 'UpsamplingBilinear2d', 'UpsamplingNearest2d', 'ZeroPad1d', 'ZeroPad2d', 'ZeroPad3d', '__builtins__', 
'__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_reduction', 
'common_types', 'factory_kwargs', 'functional', 'grad', 'init', 'intrinsic', 'modules', 'parallel', 'parameter', 'qat', 'quantizable', 'quantized', 'utils']
>>> 

2.2 tensorflow中keras中所有功能函数

>>> import tensorflow as tf
WARNING:tensorflow:From D:\Program Files (x86)\Python39\lib\site-packages\keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.

>>> keras_layers_functions = sorted(dir(tf.keras.layers))
>>> indexed_keras_layers = [(index, function_name) for index, function_name in enumerate(keras_layers_functions)]
>>> for index, function_name in indexed_keras_layers:
	print(f"{index}: {function_name}")

	
0: AbstractRNNCell
1: Activation
2: ActivityRegularization
3: Add
4: AdditiveAttention
5: AlphaDropout
6: Attention
7: Average
8: AveragePooling1D
9: AveragePooling2D
10: AveragePooling3D
11: AvgPool1D
12: AvgPool2D
13: AvgPool3D
14: BatchNormalization
15: Bidirectional
16: CategoryEncoding
17: CenterCrop
18: Concatenate
19: Conv1D
20: Conv1DTranspose
21: Conv2D
22: Conv2DTranspose
23: Conv3D
24: Conv3DTranspose
25: ConvLSTM1D
26: ConvLSTM2D
27: ConvLSTM3D
28: Convolution1D
29: Convolution1DTranspose
30: Convolution2D
31: Convolution2DTranspose
32: Convolution3D
33: Convolution3DTranspose
34: Cropping1D
35: Cropping2D
36: Cropping3D
37: Dense
38: DenseFeatures
39: DepthwiseConv1D
40: DepthwiseConv2D
41: Discretization
42: Dot
43: Dropout
44: ELU
45: EinsumDense
46: Embedding
47: Flatten
48: GRU
49: GRUCell
50: GaussianDropout
51: GaussianNoise
52: GlobalAveragePooling1D
53: GlobalAveragePooling2D
54: GlobalAveragePooling3D
55: GlobalAvgPool1D
56: GlobalAvgPool2D
57: GlobalAvgPool3D
58: GlobalMaxPool1D
59: GlobalMaxPool2D
60: GlobalMaxPool3D
61: GlobalMaxPooling1D
62: GlobalMaxPooling2D
63: GlobalMaxPooling3D
64: GroupNormalization
65: HashedCrossing
66: Hashing
67: Identity
68: Input
69: InputLayer
70: InputSpec
71: IntegerLookup
72: LSTM
73: LSTMCell
74: Lambda
75: Layer
76: LayerNormalization
77: LeakyReLU
78: LocallyConnected1D
79: LocallyConnected2D
80: Masking
81: MaxPool1D
82: MaxPool2D
83: MaxPool3D
84: MaxPooling1D
85: MaxPooling2D
86: MaxPooling3D
87: Maximum
88: Minimum
89: MultiHeadAttention
90: Multiply
91: Normalization
92: PReLU
93: Permute
94: RNN
95: RandomBrightness
96: RandomContrast
97: RandomCrop
98: RandomFlip
99: RandomHeight
100: RandomRotation
101: RandomTranslation
102: RandomWidth
103: RandomZoom
104: ReLU
105: RepeatVector
106: Rescaling
107: Reshape
108: Resizing
109: SeparableConv1D
110: SeparableConv2D
111: SeparableConvolution1D
112: SeparableConvolution2D
113: SimpleRNN
114: SimpleRNNCell
115: Softmax
116: SpatialDropout1D
117: SpatialDropout2D
118: SpatialDropout3D
119: SpectralNormalization
120: StackedRNNCells
121: StringLookup
122: Subtract
123: TextVectorization
124: ThresholdedReLU
125: TimeDistributed
126: UnitNormalization
127: UpSampling1D
128: UpSampling2D
129: UpSampling3D
130: Wrapper
131: ZeroPadding1D
132: ZeroPadding2D
133: ZeroPadding3D
134: __builtins__
135: __cached__
136: __doc__
137: __file__
138: __loader__
139: __name__
140: __package__
141: __path__
142: __spec__
143: add
144: average
145: concatenate
146: deserialize
147: dot
148: experimental
149: maximum
150: minimum
151: multiply
152: serialize
153: subtract
>>> 

2.3 tensorflow中除keras\raw_ops模块的众多函数

import tensorflow as tf  
import inspect  
  
def get_all_tensorflow_api_items():  
    # 获取tensorflow包中的所有模块  
    modules = inspect.getmembers(tf, inspect.ismodule)  
  
    # 初始化一个列表来存储所有的API项  
    api_items = []  
  
    # 遍历每个模块  
    for index, (module_name, module) in enumerate(modules):  
        # 为模块添加索引和名称  
        api_items.append((index, module_name))  
  
        # 获取模块中的所有函数、类和变量  
        members = inspect.getmembers(module, inspect.isfunction)
                  # inspect.getmembers(module, inspect.isclass)
                  # inspect.getmembers(module, inspect.isdatadescriptor)  
  
        # 遍历模块中的每个成员  
        indd = 0
        for member_index, (member_name, member) in enumerate(members):  
            # 为每个成员添加索引、模块名称和成员名称 
            if module_name == "raw_ops" or module_name.startswith("_"):
                continue
            indd += 1 
            api_items.append((indd, f"{module_name}.{member_name}"))  
    print("begin!!!!!!!!!!!------!!!!!!")
    for index, api_item in api_items:
        print(f"{index}: {api_item}")
    return api_items

if __name__ == "__main__":
    get_all_tensorflow_api_items()


begin!!!!!!!!!!!------!!!!!!
0: _API_MODULE
1: __internal__
2: __operators__
3: _api
4: _compat
5: _current_module
6: _distutils
7: _fi
8: _initializers
9: _inspect
10: _ll
11: _logging
12: _losses
13: _metrics
14: _module_util
15: _optimizers
16: _os
17: _site
18: _sys
19: _tf2
20: _typing
21: audio
1: audio.decode_wav
2: audio.encode_wav
22: autodiff
23: autograph
1: autograph.set_verbosity
2: autograph.to_code
3: autograph.to_graph
4: autograph.trace
24: bitwise
1: bitwise.bitwise_and
2: bitwise.bitwise_or
3: bitwise.bitwise_xor
4: bitwise.invert
5: bitwise.left_shift
6: bitwise.right_shift
25: compat
1: compat.as_bytes
2: compat.as_str
3: compat.as_str_any
4: compat.as_text
5: compat.dimension_at_index
6: compat.dimension_value
7: compat.forward_compatibility_horizon
8: compat.forward_compatible
9: compat.path_to_str
26: config
1: config.experimental_connect_to_cluster
2: config.experimental_connect_to_host
3: config.experimental_functions_run_eagerly
4: config.experimental_run_functions_eagerly
5: config.functions_run_eagerly
6: config.get_logical_device_configuration
7: config.get_soft_device_placement
8: config.get_visible_devices
9: config.list_logical_devices
10: config.list_physical_devices
11: config.run_functions_eagerly
12: config.set_logical_device_configuration
13: config.set_soft_device_placement
14: config.set_visible_devices
27: data
28: debugging
1: debugging.Assert
2: debugging.assert_all_finite
3: debugging.assert_equal
4: debugging.assert_greater
5: debugging.assert_greater_equal
6: debugging.assert_integer
7: debugging.assert_less
8: debugging.assert_less_equal
9: debugging.assert_near
10: debugging.assert_negative
11: debugging.assert_non_negative
12: debugging.assert_non_positive
13: debugging.assert_none_equal
14: debugging.assert_positive
15: debugging.assert_proper_iterable
16: debugging.assert_rank
17: debugging.assert_rank_at_least
18: debugging.assert_rank_in
19: debugging.assert_same_float_dtype
20: debugging.assert_scalar
21: debugging.assert_shapes
22: debugging.assert_type
23: debugging.check_numerics
24: debugging.disable_check_numerics
25: debugging.disable_traceback_filtering
26: debugging.enable_check_numerics
27: debugging.enable_traceback_filtering
28: debugging.get_log_device_placement
29: debugging.is_numeric_tensor
30: debugging.is_traceback_filtering_enabled
31: debugging.set_log_device_placement
29: distribute
1: distribute.experimental_set_strategy
2: distribute.get_replica_context
3: distribute.get_strategy
4: distribute.has_strategy
5: distribute.in_cross_replica_context
30: dtensor
31: dtypes
1: dtypes.as_dtype
2: dtypes.cast
3: dtypes.complex
4: dtypes.saturate_cast
32: errors
33: estimator
1: estimator.add_metrics
2: estimator.classifier_parse_example_spec
3: estimator.regressor_parse_example_spec
4: estimator.train_and_evaluate
34: experimental
1: experimental.async_clear_error
2: experimental.async_scope
3: experimental.dispatch_for_api
4: experimental.dispatch_for_binary_elementwise_apis
5: experimental.dispatch_for_binary_elementwise_assert_apis
6: experimental.dispatch_for_unary_elementwise_apis
7: experimental.enable_strict_mode
8: experimental.function_executor_type
9: experimental.register_filesystem_plugin
10: experimental.unregister_dispatch_for
35: feature_column
1: feature_column.bucketized_column
2: feature_column.categorical_column_with_hash_bucket
3: feature_column.categorical_column_with_identity
4: feature_column.categorical_column_with_vocabulary_file
5: feature_column.categorical_column_with_vocabulary_list
6: feature_column.crossed_column
7: feature_column.embedding_column
8: feature_column.indicator_column
9: feature_column.make_parse_example_spec
10: feature_column.numeric_column
11: feature_column.sequence_categorical_column_with_hash_bucket
12: feature_column.sequence_categorical_column_with_identity
13: feature_column.sequence_categorical_column_with_vocabulary_file
14: feature_column.sequence_categorical_column_with_vocabulary_list
15: feature_column.sequence_numeric_column
16: feature_column.shared_embeddings
17: feature_column.weighted_categorical_column
36: graph_util
1: graph_util.import_graph_def
37: image
1: image.adjust_brightness
2: image.adjust_contrast
3: image.adjust_gamma
4: image.adjust_hue
5: image.adjust_jpeg_quality
6: image.adjust_saturation
7: image.central_crop
8: image.combined_non_max_suppression
9: image.convert_image_dtype
10: image.crop_and_resize
11: image.crop_to_bounding_box
12: image.decode_and_crop_jpeg
13: image.decode_bmp
14: image.decode_gif
15: image.decode_image
16: image.decode_jpeg
17: image.decode_png
18: image.draw_bounding_boxes
19: image.encode_jpeg
20: image.encode_png
21: image.extract_glimpse
22: image.extract_jpeg_shape
23: image.extract_patches
24: image.flip_left_right
25: image.flip_up_down
26: image.generate_bounding_box_proposals
27: image.grayscale_to_rgb
28: image.hsv_to_rgb
29: image.image_gradients
30: image.is_jpeg
31: image.non_max_suppression
32: image.non_max_suppression_overlaps
33: image.non_max_suppression_padded
34: image.non_max_suppression_with_scores
35: image.pad_to_bounding_box
36: image.per_image_standardization
37: image.psnr
38: image.random_brightness
39: image.random_contrast
40: image.random_crop
41: image.random_flip_left_right
42: image.random_flip_up_down
43: image.random_hue
44: image.random_jpeg_quality
45: image.random_saturation
46: image.resize
47: image.resize_with_crop_or_pad
48: image.resize_with_pad
49: image.rgb_to_grayscale
50: image.rgb_to_hsv
51: image.rgb_to_yiq
52: image.rgb_to_yuv
53: image.rot90
54: image.sample_distorted_bounding_box
55: image.sobel_edges
56: image.ssim
57: image.ssim_multiscale
58: image.stateless_random_brightness
59: image.stateless_random_contrast
60: image.stateless_random_crop
61: image.stateless_random_flip_left_right
62: image.stateless_random_flip_up_down
63: image.stateless_random_hue
64: image.stateless_random_jpeg_quality
65: image.stateless_random_saturation
66: image.stateless_sample_distorted_bounding_box
67: image.total_variation
68: image.transpose
69: image.yiq_to_rgb
70: image.yuv_to_rgb
38: initializers
1: initializers.deserialize
2: initializers.get
3: initializers.serialize
39: io
1: io.decode_and_crop_jpeg
2: io.decode_base64
3: io.decode_bmp
4: io.decode_compressed
5: io.decode_csv
6: io.decode_gif
7: io.decode_image
8: io.decode_jpeg
9: io.decode_json_example
10: io.decode_png
11: io.decode_proto
12: io.decode_raw
13: io.deserialize_many_sparse
14: io.encode_base64
15: io.encode_jpeg
16: io.encode_png
17: io.encode_proto
18: io.extract_jpeg_shape
19: io.is_jpeg
20: io.match_filenames_once
21: io.matching_files
22: io.parse_example
23: io.parse_sequence_example
24: io.parse_single_example
25: io.parse_single_sequence_example
26: io.parse_tensor
27: io.read_file
28: io.serialize_many_sparse
29: io.serialize_sparse
30: io.serialize_tensor
31: io.write_file
32: io.write_graph
40: keras
1: keras.Input
41: linalg
1: linalg.adjoint
2: linalg.band_part
3: linalg.banded_triangular_solve
4: linalg.cholesky
5: linalg.cholesky_solve
6: linalg.cross
7: linalg.det
8: linalg.diag
9: linalg.diag_part
10: linalg.eig
11: linalg.eigh
12: linalg.eigh_tridiagonal
13: linalg.eigvals
14: linalg.eigvalsh
15: linalg.einsum
16: linalg.expm
17: linalg.eye
18: linalg.global_norm
19: linalg.inv
20: linalg.l2_normalize
21: linalg.logdet
22: linalg.logm
23: linalg.lstsq
24: linalg.lu
25: linalg.lu_matrix_inverse
26: linalg.lu_reconstruct
27: linalg.lu_solve
28: linalg.matmul
29: linalg.matrix_rank
30: linalg.matrix_transpose
31: linalg.matvec
32: linalg.norm
33: linalg.normalize
34: linalg.pinv
35: linalg.qr
36: linalg.set_diag
37: linalg.slogdet
38: linalg.solve
39: linalg.sqrtm
40: linalg.svd
41: linalg.tensor_diag
42: linalg.tensor_diag_part
43: linalg.tensordot
44: linalg.trace
45: linalg.triangular_solve
46: linalg.tridiagonal_matmul
47: linalg.tridiagonal_solve
42: lite
43: lookup
44: losses
1: losses.KLD
2: losses.MAE
3: losses.MAPE
4: losses.MSE
5: losses.MSLE
6: losses.binary_crossentropy
7: losses.binary_focal_crossentropy
8: losses.categorical_crossentropy
9: losses.categorical_focal_crossentropy
10: losses.categorical_hinge
11: losses.cosine_similarity
12: losses.deserialize
13: losses.get
14: losses.hinge
15: losses.huber
16: losses.kl_divergence
17: losses.kld
18: losses.kullback_leibler_divergence
19: losses.log_cosh
20: losses.logcosh
21: losses.mae
22: losses.mape
23: losses.mean_absolute_error
24: losses.mean_absolute_percentage_error
25: losses.mean_squared_error
26: losses.mean_squared_logarithmic_error
27: losses.mse
28: losses.msle
29: losses.poisson
30: losses.serialize
31: losses.sparse_categorical_crossentropy
32: losses.squared_hinge
45: math
1: math.abs
2: math.accumulate_n
3: math.acos
4: math.acosh
5: math.add
6: math.add_n
7: math.angle
8: math.approx_max_k
9: math.approx_min_k
10: math.argmax
11: math.argmin
12: math.asin
13: math.asinh
14: math.atan
15: math.atan2
16: math.atanh
17: math.bessel_i0
18: math.bessel_i0e
19: math.bessel_i1
20: math.bessel_i1e
21: math.betainc
22: math.bincount
23: math.ceil
24: math.confusion_matrix
25: math.conj
26: math.cos
27: math.cosh
28: math.count_nonzero
29: math.cumprod
30: math.cumsum
31: math.cumulative_logsumexp
32: math.digamma
33: math.divide
34: math.divide_no_nan
35: math.equal
36: math.erf
37: math.erfc
38: math.erfcinv
39: math.erfinv
40: math.exp
41: math.expm1
42: math.floor
43: math.floordiv
44: math.floormod
45: math.greater
46: math.greater_equal
47: math.igamma
48: math.igammac
49: math.imag
50: math.in_top_k
51: math.invert_permutation
52: math.is_finite
53: math.is_inf
54: math.is_nan
55: math.is_non_decreasing
56: math.is_strictly_increasing
57: math.l2_normalize
58: math.lbeta
59: math.less
60: math.less_equal
61: math.lgamma
62: math.log
63: math.log1p
64: math.log_sigmoid
65: math.log_softmax
66: math.logical_and
67: math.logical_not
68: math.logical_or
69: math.logical_xor
70: math.maximum
71: math.minimum
72: math.mod
73: math.multiply
74: math.multiply_no_nan
75: math.ndtri
76: math.negative
77: math.nextafter
78: math.not_equal
79: math.polygamma
80: math.polyval
81: math.pow
82: math.real
83: math.reciprocal
84: math.reciprocal_no_nan
85: math.reduce_all
86: math.reduce_any
87: math.reduce_euclidean_norm
88: math.reduce_logsumexp
89: math.reduce_max
90: math.reduce_mean
91: math.reduce_min
92: math.reduce_prod
93: math.reduce_std
94: math.reduce_sum
95: math.reduce_variance
96: math.rint
97: math.round
98: math.rsqrt
99: math.scalar_mul
100: math.segment_max
101: math.segment_mean
102: math.segment_min
103: math.segment_prod
104: math.segment_sum
105: math.sigmoid
106: math.sign
107: math.sin
108: math.sinh
109: math.sobol_sample
110: math.softmax
111: math.softplus
112: math.softsign
113: math.sqrt
114: math.square
115: math.squared_difference
116: math.subtract
117: math.tan
118: math.tanh
119: math.top_k
120: math.truediv
121: math.unsorted_segment_max
122: math.unsorted_segment_mean
123: math.unsorted_segment_min
124: math.unsorted_segment_prod
125: math.unsorted_segment_sqrt_n
126: math.unsorted_segment_sum
127: math.xdivy
128: math.xlog1py
129: math.xlogy
130: math.zero_fraction
131: math.zeta
46: metrics
1: metrics.KLD
2: metrics.MAE
3: metrics.MAPE
4: metrics.MSE
5: metrics.MSLE
6: metrics.binary_accuracy
7: metrics.binary_crossentropy
8: metrics.binary_focal_crossentropy
9: metrics.categorical_accuracy
10: metrics.categorical_crossentropy
11: metrics.categorical_focal_crossentropy
12: metrics.deserialize
13: metrics.get
14: metrics.hinge
15: metrics.kl_divergence
16: metrics.kld
17: metrics.kullback_leibler_divergence
18: metrics.log_cosh
19: metrics.logcosh
20: metrics.mae
21: metrics.mape
22: metrics.mean_absolute_error
23: metrics.mean_absolute_percentage_error
24: metrics.mean_squared_error
25: metrics.mean_squared_logarithmic_error
26: metrics.mse
27: metrics.msle
28: metrics.poisson
29: metrics.serialize
30: metrics.sparse_categorical_accuracy
31: metrics.sparse_categorical_crossentropy
32: metrics.sparse_top_k_categorical_accuracy
33: metrics.squared_hinge
34: metrics.top_k_categorical_accuracy
47: mlir
48: nest
1: nest.assert_same_structure
2: nest.flatten
3: nest.is_nested
4: nest.map_structure
5: nest.pack_sequence_as
49: nn
1: nn.all_candidate_sampler
2: nn.approx_max_k
3: nn.approx_min_k
4: nn.atrous_conv2d
5: nn.atrous_conv2d_transpose
6: nn.avg_pool
7: nn.avg_pool1d
8: nn.avg_pool2d
9: nn.avg_pool3d
10: nn.batch_norm_with_global_normalization
11: nn.batch_normalization
12: nn.bias_add
13: nn.collapse_repeated
14: nn.compute_accidental_hits
15: nn.compute_average_loss
16: nn.conv1d
17: nn.conv1d_transpose
18: nn.conv2d
19: nn.conv2d_transpose
20: nn.conv3d
21: nn.conv3d_transpose
22: nn.conv_transpose
23: nn.convolution
24: nn.crelu
25: nn.ctc_beam_search_decoder
26: nn.ctc_greedy_decoder
27: nn.ctc_loss
28: nn.ctc_unique_labels
29: nn.depth_to_space
30: nn.depthwise_conv2d
31: nn.depthwise_conv2d_backprop_filter
32: nn.depthwise_conv2d_backprop_input
33: nn.dilation2d
34: nn.dropout
35: nn.elu
36: nn.embedding_lookup
37: nn.embedding_lookup_sparse
38: nn.erosion2d
39: nn.fixed_unigram_candidate_sampler
40: nn.fractional_avg_pool
41: nn.fractional_max_pool
42: nn.gelu
43: nn.in_top_k
44: nn.isotonic_regression
45: nn.l2_loss
46: nn.l2_normalize
47: nn.leaky_relu
48: nn.learned_unigram_candidate_sampler
49: nn.local_response_normalization
50: nn.log_poisson_loss
51: nn.log_softmax
52: nn.lrn
53: nn.max_pool
54: nn.max_pool1d
55: nn.max_pool2d
56: nn.max_pool3d
57: nn.max_pool_with_argmax
58: nn.moments
59: nn.nce_loss
60: nn.normalize_moments
61: nn.pool
62: nn.relu
63: nn.relu6
64: nn.safe_embedding_lookup_sparse
65: nn.sampled_softmax_loss
66: nn.scale_regularization_loss
67: nn.selu
68: nn.separable_conv2d
69: nn.sigmoid
70: nn.sigmoid_cross_entropy_with_logits
71: nn.silu
72: nn.softmax
73: nn.softmax_cross_entropy_with_logits
74: nn.softplus
75: nn.softsign
76: nn.space_to_batch
77: nn.space_to_depth
78: nn.sparse_softmax_cross_entropy_with_logits
79: nn.sufficient_statistics
80: nn.swish
81: nn.tanh
82: nn.top_k
83: nn.weighted_cross_entropy_with_logits
84: nn.weighted_moments
85: nn.with_space_to_batch
86: nn.zero_fraction
50: optimizers
1: optimizers.deserialize
2: optimizers.get
3: optimizers.serialize
51: profiler
52: quantization
1: quantization.dequantize
2: quantization.fake_quant_with_min_max_args
3: quantization.fake_quant_with_min_max_args_gradient
4: quantization.fake_quant_with_min_max_vars
5: quantization.fake_quant_with_min_max_vars_gradient
6: quantization.fake_quant_with_min_max_vars_per_channel
7: quantization.fake_quant_with_min_max_vars_per_channel_gradient
8: quantization.quantize
9: quantization.quantize_and_dequantize
10: quantization.quantize_and_dequantize_v2
11: quantization.quantized_concat
53: queue
54: ragged
1: ragged.boolean_mask
2: ragged.constant
3: ragged.cross
4: ragged.cross_hashed
5: ragged.map_flat_values
6: ragged.range
7: ragged.row_splits_to_segment_ids
8: ragged.segment_ids_to_row_splits
9: ragged.stack
10: ragged.stack_dynamic_partitions
55: random
1: random.all_candidate_sampler
2: random.categorical
3: random.create_rng_state
4: random.fixed_unigram_candidate_sampler
5: random.fold_in
6: random.gamma
7: random.get_global_generator
8: random.learned_unigram_candidate_sampler
9: random.log_uniform_candidate_sampler
10: random.normal
11: random.poisson
12: random.set_global_generator
13: random.set_seed
14: random.shuffle
15: random.split
16: random.stateless_binomial
17: random.stateless_categorical
18: random.stateless_gamma
19: random.stateless_normal
20: random.stateless_parameterized_truncated_normal
21: random.stateless_poisson
22: random.stateless_truncated_normal
23: random.stateless_uniform
24: random.truncated_normal
25: random.uniform
26: random.uniform_candidate_sampler
56: raw_ops
57: saved_model
1: saved_model.contains_saved_model
2: saved_model.load
3: saved_model.save
58: security
59: sets
1: sets.difference
2: sets.intersection
3: sets.size
4: sets.union
60: signal
1: signal.dct
2: signal.fft
3: signal.fft2d
4: signal.fft3d
5: signal.fftnd
6: signal.fftshift
7: signal.frame
8: signal.hamming_window
9: signal.hann_window
10: signal.idct
11: signal.ifft
12: signal.ifft2d
13: signal.ifft3d
14: signal.ifftnd
15: signal.ifftshift
16: signal.inverse_mdct
17: signal.inverse_stft
18: signal.inverse_stft_window_fn
19: signal.irfft
20: signal.irfft2d
21: signal.irfft3d
22: signal.irfftnd
23: signal.kaiser_bessel_derived_window
24: signal.kaiser_window
25: signal.linear_to_mel_weight_matrix
26: signal.mdct
27: signal.mfccs_from_log_mel_spectrograms
28: signal.overlap_and_add
29: signal.rfft
30: signal.rfft2d
31: signal.rfft3d
32: signal.rfftnd
33: signal.stft
34: signal.vorbis_window
61: sparse
1: sparse.add
2: sparse.bincount
3: sparse.concat
4: sparse.cross
5: sparse.cross_hashed
6: sparse.expand_dims
7: sparse.eye
8: sparse.fill_empty_rows
9: sparse.from_dense
10: sparse.map_values
11: sparse.mask
12: sparse.maximum
13: sparse.minimum
14: sparse.reduce_max
15: sparse.reduce_sum
16: sparse.reorder
17: sparse.reset_shape
18: sparse.reshape
19: sparse.retain
20: sparse.segment_mean
21: sparse.segment_sqrt_n
22: sparse.segment_sum
23: sparse.slice
24: sparse.softmax
25: sparse.sparse_dense_matmul
26: sparse.split
27: sparse.to_dense
28: sparse.to_indicator
29: sparse.transpose
62: strings
1: strings.as_string
2: strings.bytes_split
3: strings.format
4: strings.join
5: strings.length
6: strings.lower
7: strings.ngrams
8: strings.reduce_join
9: strings.regex_full_match
10: strings.regex_replace
11: strings.split
12: strings.strip
13: strings.substr
14: strings.to_hash_bucket
15: strings.to_hash_bucket_fast
16: strings.to_hash_bucket_strong
17: strings.to_number
18: strings.unicode_decode
19: strings.unicode_decode_with_offsets
20: strings.unicode_encode
21: strings.unicode_script
22: strings.unicode_split
23: strings.unicode_split_with_offsets
24: strings.unicode_transcode
25: strings.unsorted_segment_join
26: strings.upper
63: summary
1: summary.audio
2: summary.create_file_writer
3: summary.create_noop_writer
4: summary.flush
5: summary.graph
6: summary.histogram
7: summary.image
8: summary.record_if
9: summary.scalar
10: summary.should_record_summaries
11: summary.text
12: summary.trace_export
13: summary.trace_off
14: summary.trace_on
15: summary.write
64: sysconfig
1: sysconfig.get_build_info
2: sysconfig.get_compile_flags
3: sysconfig.get_include
4: sysconfig.get_lib
5: sysconfig.get_link_flags
65: test
1: test.assert_equal_graph_def
2: test.benchmark_config
3: test.compute_gradient
4: test.create_local_cluster
5: test.disable_with_predicate
6: test.gpu_device_name
7: test.is_built_with_cuda
8: test.is_built_with_gpu_support
9: test.is_built_with_rocm
10: test.is_built_with_xla
11: test.is_gpu_available
12: test.main
13: test.with_eager_op_as_function
66: tools
67: tpu
68: train
1: train.checkpoints_iterator
2: train.get_checkpoint_state
3: train.latest_checkpoint
4: train.list_variables
5: train.load_checkpoint
6: train.load_variable
69: tsl
70: types
71: version
72: xla

鉴于tensorflow模块函数众多,特此列出前100常用或重要的函数

tf.Tensor - 表示多维数组的对象。
tf.constant - 创建一个常量张量。
tf.Variable - 可变张量类,用于存储模型参数。
tf.function - 将Python函数转换为TensorFlow图函数的装饰器。
tf.keras.Sequential - 线性堆叠模型的类。
tf.keras.Model - 构建自定义模型的类。
tf.keras.layers.Dense - 全连接层。
tf.keras.layers.Conv2D - 二维卷积层。
tf.keras.layers.MaxPooling2D - 最大池化层。
tf.keras.layers.BatchNormalization - 批量归一化层。
tf.keras.layers.Activation - 激活函数层。
tf.keras.losses.SparseCategoricalCrossentropy - 稀疏分类交叉熵损失。
tf.keras.losses.MeanSquaredError - 均方误差损失。
tf.keras.losses.BinaryCrossentropy - 二元交叉熵损失。
tf.keras.optimizers.SGD - 随机梯度下降优化器。
tf.keras.optimizers.Adam - Adam优化器。
tf.keras.optimizers.RMSprop - RMSprop优化器。
tf.data.Dataset - 数据集类,用于构建输入管道。
tf.data.map - 对数据集中的每个元素应用函数。
tf.data.batch - 将数据集中的元素组合成批次。
tf.data.shuffle - 随机打乱数据集中的元素。
tf.reduce_mean - 计算张量的均值。
tf.reduce_sum - 计算张量的总和。
tf.reduce_max - 计算张量的最大值。
tf.reduce_min - 计算张量的最小值。
tf.math.softmax - 计算softmax激活值。
tf.math.sigmoid - 计算sigmoid激活值。
tf.math.relu - 计算ReLU激活值。
tf.nn.conv2d - 对4D输入进行2D卷积。
tf.nn.max_pool2d - 对4D输入进行最大池化。
tf.nn.softmax_cross_entropy_with_logits - 计算softmax交叉熵。
tf.nn.sigmoid_cross_entropy_with_logits - 计算sigmoid交叉熵。
tf.reshape - 重新塑形张量。
tf.concat - 沿着指定轴连接张量序列。
tf.split - 将张量分割成多个子张量。
tf.stack - 沿着新轴连接张量序列。
tf.squeeze - 从张量形状中移除单维度条目。
tf.expand_dims - 在张量的形状中插入一个维度。
tf.transpose - 置换张量的维度。
tf.reduce_any - 如果张量中有任何元素为真,则返回True。
tf.reduce_all - 如果张量中的所有元素都为真,则返回True。
tf.greater - 对两个张量进行元素级比较。
tf.less - 对两个张量进行元素级比较。
tf.equal - 对两个张量进行元素级比较。
tf.where - 返回输入张量中的元素为True的位置。
tf.gather - 从参数params中根据indices收集切片。
tf.scatter_add - 这个函数用于根据指定的索引在张量中添加值。
tf.scatter_nd - 根据指定的索引在tensor中更新值。
tf.gather_nd - 根据给定的索引从tensor中收集切片。
tf.scatter_add - 根据指定的索引在tensor中添加值。
tf.reduce_prod - 计算张量中所有元素的乘积。
tf.math.is_finite - 检查张量中的元素是否是有限的。
tf.math.is_inf - 检查张量中的元素是否是正无穷或负无穷。
tf.math.is_nan - 检查张量中的元素是否是NaN。
tf.reduce_any - 如果张量中有任何元素为真,则返回True(已提及)。
tf.reduce_all - 如果张量中的所有元素都为真,则返回True(已提及)。
tf.logical_and - 对两个张量进行元素级的逻辑与操作。
tf.logical_or - 对两个张量进行元素级的逻辑或操作。
tf.logical_not - 对张量进行元素级的逻辑非操作。
tf.math.ceil - 向上取整。
tf.math.floor - 向下取整。
tf.math.round - 四舍五入到最接近的整数。
tf.cast - 将张量的数据类型转换为指定类型。
tf.reduce_logsumexp - 计算张量中元素的log-sum-exp。
tf.clip_by_value - 将张量中的值限制在一个范围内。
tf.clip_by_norm - 将张量的L2范数限制在一个范围内。
tf.reduce_count_nonzero - 计算张量中非零元素的数量。
tf.unique - 找出张量中的唯一元素及其索引。
tf.reverse - 沿着指定轴反转张量。
tf.tile - 构造一个张量,将输入张量重复指定的次数。
tf.pad - 在张量的边界填充零或其他值。
tf.reshape - 重新塑形张量(已提及)。
tf.squeeze - 从张量形状中移除单维度条目(已提及)。
tf.expand_dims - 在张量的形状中插入一个维度(已提及)。
tf.concat - 沿着指定轴连接张量序列(已提及)。
tf.split - 将张量分割成多个子张量(已提及)。
tf.stack - 沿着新轴连接张量序列(已提及)。
tf.transpose - 置换张量的维度(已提及)。
tf.random.normal - 生成服从正态分布的随机数。
tf.random.uniform - 生成服从均匀分布的随机数。
tf.random.shuffle - 随机打乱张量的元素。
tf.random.categorical - 生成服从分类分布的随机数。
tf.Variable.assign - 将新值赋给变量。
tf.Variable.assign_add - 将变量的当前值加上一个值。
tf.Variable.assign_sub - 从变量的当前值中减去一个值。
tf.Variable.scatter_sub - 从张量中的选定位置减去值。
tf.Variable.scatter_add - 向张量中的选定位置添加值。
tf.print - 打印张量的值。
tf.debugging.assert_equal - 断言两个张量相等。
tf.debugging.assert_greater - 断言第一个张量大于第二个张量。
tf.debugging.assert_less - 断言第一个张量小于第二个张量。
tf.debugging.assert_non_negative - 断言张量中的所有元素都是非负的。
tf.debugging.assert_positive - 断言张量中的所有
tf.debugging.assert_integer_formed - 断言张量由整数形成。
tf.debugging.assert_rank - 断言张量具有指定的秩(维度数)。
tf.debugging.assert_type - 断言张量具有指定的数据类型。
tf.reduce_min - 计算张量的最小值(已提及)。
tf.reduce_max - 计算张量的最大值(已提及)。
tf.reduce_mean - 计算张量的均值(已提及)。
tf.reduce_sum - 计算张量的总和(已提及)。

2.4 compat模块中众多函数

tensorflow.compat 模块是为了保持 TensorFlow 1.x 和 2.x 之间的兼容性而设计的。由于 TensorFlow 2.x 对 API 进行了大量重构和简化,compat 模块提供了从 TensorFlow 2.x 代码调用 TensorFlow 1.x 风格函数的方式。请注意,随着 TensorFlow 2.x 的发展,越来越多的功能被直接集成到核心库中,因此 compat 模块的使用可能会逐渐减少。

以下是 tensorflow.compat 模块中常用的一些函数和类

tf.compat.v1.disable_eager_execution(): 禁用 Eager Execution,使 TensorFlow 回到 1.x 的图执行模式。

tf.compat.v1.enable_eager_execution(): 启用 Eager Execution。

tf.compat.v1.Session(): 创建一个 TensorFlow 1.x 风格的会话。

tf.compat.v1.run(): 在 TensorFlow 1.x 会话中执行操作。

tf.compat.v1.placeholder(): 创建一个占位符,用于在图中表示输入。

tf.compat.v1.placeholder_with_default(): 创建一个具有默认值的占位符。

tf.compat.v1.Variable(): 创建一个 TensorFlow 1.x 风格的变量。

tf.compat.v1.global_variables_initializer(): 返回一个操作,用于初始化所有全局变量。

tf.compat.v1.local_variables_initializer(): 返回一个操作,用于初始化所有本地变量。

tf.compat.v1.train.Saver(): 创建一个 Saver 对象,用于保存和恢复模型。

tf.compat.v1.train.start_queue_runners(): 启动所有队列运行器。

tf.compat.v1.train.Supervisor(): 创建一个 Supervisor 对象,用于管理会话和队列。

tf.compat.v1.control_dependencies(): 创建一个上下文管理器,用于指定控制依赖关系。

tf.compat.v1.data.Dataset: TensorFlow 1.x 风格的数据集 API。

tf.compat.v1.data.Dataset.from_tensor_slices(): 从张量切片创建数据集。

tf.compat.v1.data.Dataset.map(): 对数据集中的每个元素应用函数。

tf.compat.v1.data.Dataset.batch(): 将数据集中的元素组合成批次。

tf.compat.v1.data.Dataset.prefetch(): 预取数据集中的元素。

tf.compat.v1.image.resize_images(): 调整图像大小。

tf.compat.v1.image.resize_image_with_crop_or_pad(): 裁剪或填充图像以匹配目标大小。

tf.compat.v1.nn.softmax(): 对张量应用 softmax 函数。

tf.compat.v1.nn.sigmoid(): 对张量应用 sigmoid 函数。

tf.compat.v1.nn.relu(): 对张量应用 ReLU 函数。

tf.compat.v1.nn.conv2d(): 对 4D 输入执行 2D 卷积。

tf.compat.v1.nn.max_pool(): 对 4D 输入执行最大池化。

tf.compat.v1.nn.dropout(): 对输入张量应用 dropout。

tf.compat.v1.nn.batch_norm_with_global_normalization(): 对输入执行批标准化。

tf.compat.v1.nn.l2_loss(): 计算张量的 L2 损失。

tf.compat.v1.nn.sigmoid_cross_entropy_with_logits(): 计算 sigmoid 交叉熵损失。

tf.compat.v1.nn.softmax_cross_entropy_with_logits(): 计算 softmax 交叉熵损失。

tf.compat.v1.metrics.accuracy(): 计算准确率。
tf.compat.v1.metrics.mean(): 计算均值。

tf.compat.v1.metrics.mean_squared_error(): 计算均方误差。

tf.compat.v1.metrics.precision(): 计算精确度。

tf.compat.v1.metrics.recall(): 计算召回率。

tf.compat.v1.metrics.auc(): 计算 AUC(Area Under the Curve)值。

tf.compat.v1.reduce_mean(): 计算张量的均值(与 tf.reduce_mean 相同,但用于兼容性)。

tf.compat.v1.reduce_sum(): 计算张量的总和(与 tf.reduce_sum 相同,但用于兼容性)。

tf.compat.v1.reduce_max(): 计算张量的最大值(与 tf.reduce_max 相同,但用于兼容性)。

tf.compat.v1.reduce_min(): 计算张量的最小值(与 tf.reduce_min 相同,但用于兼容性)。

tf.compat.v1.reduce_all(): 如果张量中的所有元素均为 True,则返回 True。

tf.compat.v1.reduce_any(): 如果张量中有任何元素为 True,则返回 True。

tf.compat.v1.argmax(): 返回张量中最大值的索引。

tf.compat.v1.argmin(): 返回张量中最小值的索引。

tf.compat.v1.constant(): 创建一个常量张量。

tf.compat.v1.placeholder_with_default(): 创建一个具有默认值的占位符(与 tf.compat.v1.placeholder_with_default 相同,但用于兼容性)。

tf.compat.v1.sparse.sparse_tensor_to_dense(): 将稀疏张量转换为密集张量。

tf.compat.v1.sparse.to_dense(): 将稀疏张量转换为密集张量(与 tf.compat.v1.sparse.sparse_tensor_to_dense 相同,但用于兼容性)。

tf.compat.v1.nn.bias_add(): 向张量添加偏差。

tf.compat.v1.nn.elu(): 对张量应用 ELU(Exponential Linear Unit)激活函数。

tf.compat.v1.nn.leaky_relu(): 对张量应用 Leaky ReLU 激活函数。

tf.compat.v1.nn.parametrized_truncated_normal(): 生成截断的正态分布随机数。

tf.compat.v1.nn.quantized_avg_pool(): 对输入执行量化平均池化。

tf.compat.v1.nn.quantized_batch_norm_with_global_normalization(): 对输入执行量化批标准化。

tf.compat.v1.nn.quantized_conv2d(): 对输入执行量化卷积。
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值