tensorflow基本用法

本文详细介绍了使用TensorFlow进行基本数学运算的方法,包括加减乘除、指数与对数运算,以及变量赋值。同时,深入探讨了向量与矩阵的运算,如向量乘法、矩阵转置、叉乘、矩阵乘法等,并展示了如何进行求和、求平均值、最大值索引查找及类型转换等操作。
import tensorflow as tf

c1 = tf.constant(9.5,dtype=tf.float32)#常量
c2 = tf.constant(10,dtype=tf.int32)#常量
a = tf.Variable(5.8)#变量
b = tf.Variable(2.9)
x = tf.Variable(5.8)#变量
y = tf.Variable(2.9)
sum = tf.Variable(0, name="sum")
result = tf.Variable(1, name="result")

f = tf.Variable([[2., 5., 4.],
                 [1., 3., 6.]])
f2 = tf.Variable([[2., 3.],
                 [1., 2.],
                 [3., 1.]])
vector1 = tf.constant([3.,3.]) #这里只有一对中括号 [],就是向量
vector2 = tf.constant([1.,2.])
result3 = tf.multiply(vector1,vector2) #向量乘法。tf.multiply()
result4 = tf.multiply(vector2,vector1)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
r3 = sess.run(result3)
r4 = sess.run(result4)
print(r3,'\n',r4)

#tf.add 加法函数
print("加法", sess.run(tf.add(a,b))) # 求和
#tf.subtract 减法函数
print("减法", sess.run(tf.subtract(a,c1))) #减法
#tf.multiply 乘法函数
print("乘法",sess.run(tf.multiply(a,b))) # 乘积
#tf.divde   除法函数
print("除法",sess.run(tf.divide(a,2.0))) #除法
print("除法",sess.run(tf.div(a,2.0))) #除法
## 幂指对数操作符:^ ^2 ^0.5 e^ ln
tf.pow(x, y, name=None)        # 幂次方
tf.square(x, name=None)        # 平方
tf.sqrt(x, name=None)          # 开根号,必须传入浮点数或复数
tf.exp(x, name=None)           # 计算 e 的次方
tf.log(x, name=None)           # 以 e 为底,必须传入浮点数或复数


#tf.assign 赋值函数
for i in range(101):
    sess.run(tf.assign(sum, tf.add(sum, i)))
print('1到100的和:', sess.run(sum))

for i in range(1, 11):
    sess.run(tf.assign(result, tf.multiply(result, i)))
print('1到10的乘积:', sess.run(result))

print("f:" ,sess.run(f))
print("转置:", sess.run(tf.transpose(f))) #矩阵转置
print("叉乘:", sess.run(tf.multiply(f, 2))) #叉乘
print("矩阵乘:", sess.run(tf.matmul(f,f2))) #矩阵乘法
print("求和reduce_sum所有", sess.run(tf.reduce_sum(f)))
print("求和reduce_sum按行", sess.run(tf.reduce_sum(f, axis=1)))
print("求和reduce_sum按列", sess.run(tf.reduce_sum(f, axis=0)))

print('行向量最大值的下标argmax=', sess.run(tf.argmax(f, axis=1)))             #行向量最大值的下标
print('类型转换(布尔到浮点数)cast  ',sess.run(tf.cast(1 > 0.5, dtype=tf.float32)))  #类型转换
print('cast  ',sess.run(tf.cast(0.1 > 0.5, dtype=tf.float32)))  #类型转换
print('比较(真) ', sess.run(tf.equal(1.0,1))) #比较
print('比较(假) ', sess.run(tf.equal(1.0,1.0))) #比较
print('比较(真) ', sess.run(tf.equal(0, False))) #比较
print('所有元素平均值reduce_mean=', sess.run(tf.reduce_mean(f)))      #所有元素平均值
print('列向量平均值reduce_mean(0)=', sess.run(tf.reduce_mean(f,0))) #列向量平均值
print('行向量平均值reduce_mean(1)=', sess.run(tf.reduce_mean(f,1))) #行向量平均值




### TensorFlow基本用法入门 TensorFlow是一个开源的机器学习框架,广泛应用于构建和训练各种类型的模型。以下是关于TensorFlow基本用法的一些核心概念和操作: #### 1. 安装TensorFlow 在使用TensorFlow之前,需要先安装它。可以通过pip命令来完成安装: ```bash pip install tensorflow ``` 确认安装成功后可以运行以下代码验证版本号: ```python import tensorflow as tf print(tf.__version__) ``` 此部分未涉及具体引用。 #### 2. 创建张量 (Tensors) 张量是TensorFlow中的基础数据结构,类似于NumPy数组。 ```python # 创建常量张量 tensor_a = tf.constant([[1, 2], [3, 4]], dtype=tf.int32) # 打印张量形状和内容 print(tensor_a.shape) # 输出: (2, 2)[^1] print(tensor_a.numpy()) # 转换为numpy array并打印[^2] ``` #### 3. 构建计算图 (Graphs and Sessions) 早期版本的TensorFlow依赖于显式的图定义和会话管理。虽然现代版本更倾向于即时执行模式(eager execution),但在某些场景下仍需理解这一机制。 - **创建计算图** ```python graph = tf.Graph() with graph.as_default(): a = tf.placeholder(tf.float32, shape=[None, 3]) # 占位符用于输入数据[^1] b = tf.Variable(0.5, name='b') # 可变参数初始化 ``` - **启动会话(Session)** 并运行图 ```python init_op = tf.global_variables_initializer() # 初始化变量 with tf.Session(graph=graph) as sess: sess.run(init_op) # 执行初始化操作 result = sess.run(b + 1) # 计算表达式的结果[^2] print(result) ``` 注意,在TensorFlow 2.x中,默认启用了eager execution,简化了许多复杂流程。 #### 4. 使用Keras API进行高层抽象开发 对于初学者来说,推荐利用内置的`tf.keras`模块实现神经网络的设计与训练过程。下面展示如何建立简单的全连接层模型: ```python model = tf.keras.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']) # 性能评估指标设置 history = model.fit(x_train, y_train, epochs=5) # 开始训练循环 test_loss, test_acc = model.evaluate(x_test, y_test) # 测试集上的表现分析 ``` 以上介绍了TensorFlow的基础组件及其典型应用方式,涵盖了从环境搭建到实际项目实践的关键环节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值