Tensflow学习笔记
import tensorflow as tf
sess=tf.compat.v1.Session()
a=tf.constant(32) #创建常量
b=tf.constant(10) #创建常量
#加法a+b+b
d=tf.add_n([a,b,b])
print(d)
运行结果:
Tensor("AddN_3:0", shape=(), dtype=int32)
#减法a-b
e=tf.subtract(a,b)
print(b)
运行结果:
Tensor("Const_17:0", shape=(), dtype=int32)
#乘法a*b
f=tf.multiply(a,b)
print(f)
运行结果:
Tensor("Mul_3:0", shape=(), dtype=int32)
#除法a/b
g=tf.divide(a,b)
print(g)
运行结果:
Tensor("truediv_6:0", shape=(), dtype=float64)
#求余
h=tf.truncatemod(a,b)
print(h)
运行结果:
Tensor("TruncateMod_3:0", shape=(), dtype=int32)
#数值类型转换
a_float=tf.cast(a,dtype=tf.float32)
b_float=tf.cast(b,dtype=tf.float32)
#sin(a)
i=tf.sin(a_float)
print(i)
运行结果:
Tensor("Sin_3:0", shape=(), dtype=float32)
#exp(1/a)
j=tf.exp(tf.divide(1.0,a_float))
print(j)
运行结果:
Tensor("Exp_3:0", shape=(), dtype=float32)
#i+log(i)
k=tf.add(i,tf.math.log(i))
print(k)
运行结果:
Tensor("Add_3:0", shape=(), dtype=float32)
#tensorflow矩阵及运算
#从4维向量生成(2,2)的矩阵
mat_a=tf.constant([1,2,3,4])
mat_a=tf.reshape(mat_a,(2,2))
#生成2*3的矩阵
mat_b=tf.constant([1,3,5,7,9,11])
mat_b=tf.reshape(mat_b,(2,3))
#矩阵乘法
mat_c=tf.matmul(mat_a,mat_b)
#从4维向量生成(2,2)的矩阵
mat_a=tf.constant([1,2,3,4])
mat_a=tf.reshape(mat_a,(2,2))
print('mat_a:\n',sess.run(mat_a))
运行结果:
mat_a: [[1 2] [3 4]]
#生成2*3的矩阵
mat_b=tf.constant([1,3,5,7,9,11])
mat_b=tf.reshape(mat_b,(2,3))
print('mat_b:\n',sess.run(mat_b))
运行结果:
mat_b: [[ 1 3 5] [ 7 9 11]]
#矩阵乘法
mat_c=tf.matmul(mat_a,mat_b)
print('mat_c:\n',sess.run(mat_c))
运行结果:
mat_c: [[15 21 27] [31 45 59]]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异