当前位置: 首页 > article >正文

TensorFlow之常量的使用1

目录

  • 前言
  • 示例
    • 示例1
    • 示例2
    • 示例3

前言

TensorFlow中定义的数据叫做Tensor(张量), Tensor又分为常量和变量。
常量一旦定义值不能改变。使用tf.constant定义常量。

示例

示例1

使用tf.constant定义常量。

import tensorflow as tf

t = tf.constant([[1., 2., 3.], [4., 5., 6.]])

# 可以像numpy的ndarray一样使用tensor
print(t)
print(t[:, 1:])
print(t[..., 1]) # 或t[:, 1]


print(t+10) # 每个元素都加10
print(tf.square(t)) # 每个元素都做平方
print(t @ tf.transpose(t)) # @表示矩阵的点乘

结果如下:

tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[2. 3.]
 [5. 6.]], shape=(2, 2), dtype=float32)
tf.Tensor([2. 5.], shape=(2,), dtype=float32)
tf.Tensor(
[[11. 12. 13.]
 [14. 15. 16.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[ 1.  4.  9.]
 [16. 25. 36.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[14. 32.]
 [32. 77.]], shape=(2, 2), dtype=float32)

示例2

常量tensor和numpy中的ndarray的转化:

import tensorflow as tf
import numpy as np

t = tf.constant([[1., 2., 3.], [4., 5., 6.]])

# .numpy()可以把tensor转化为ndarray
print(t.numpy())
print(np.square(t)) 
np_t = np.array([[1., 2., 3.], [4., 5., 6.]])
# 直接使用ndarray生成一个tensor
print(tf.constant(np_t))

结果如下:

[[1. 2. 3.]
 [4. 5. 6.]]
[[ 1.  4.  9.]
 [16. 25. 36.]]
tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]], shape=(2, 3), dtype=float64)

示例3

生成标量:

import tensorflow as tf

# scalar
t = tf.constant(2.718)
print(t.numpy())
print(t.shape)

结果如下:

2.718
()

http://www.kler.cn/a/614045.html

相关文章:

  • CentOS 7 换源
  • 怎么使用pm2启动和暂停后端程序(后端架构nodejs+koa)
  • 前端 技术栈
  • spring-security原理与应用系列:核心过滤器
  • ARCGIS PRO SDK VB2022 图层要素类类型判断
  • WPF ContentTemplate
  • JavaScript网页设计高级案例:构建交互式图片画廊
  • 阀门流量控制系统MATLAB仿真PID
  • 上海做一场公关活动,有哪些媒体可以邀请?
  • 如何让 history 记录命令执行时间?Linux/macOS 终端时间戳设置指南
  • 蓝桥杯 数三角
  • 【Qt】程序加入开机自启动
  • 简单总结比较TCP,UDP,Socket协议
  • 05-SpringBoot3入门-整合SpringMVC(配置静态资源、拦截器)
  • HarmonyOS主题管理工具封装:动态切换、持久化存储与常见问题解析
  • Springboot 学习 之 Shardingsphere 按照日期水平分表(二)
  • 数据结构之多项式相加的链表实现
  • Spring Cloud ReactorServiceInstanceLoadBalancer 自定义负载均衡
  • BoomCut AI 技术创建本地化的营销视频
  • 质量工程师的2025:从“找bug“到“造质量“的职业进化