tensorflow2.2.0入门学习

本文详细介绍TensorFlow的基础操作,包括张量的创建与处理、数学运算、常见层与模型的构建方式,如Sequentialmodel、Functionalmodel及Subclassingmodel。通过实例演示如何运用TensorFlow进行文本分类任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tensorflow安装教程

基础

import tensorflow as tf    #定义tensorflow为tf
print(tf.__version__)   #查看tensorflow版本
print(tf.test.is_gpu_available())   #查看tensorflow是否为GPU版本

#rank 0  张量
mammal = tf.Variable("Elephant", tf.string)   #0阶,字符类型,字符串
tf.print(tf.rank(mammal))    #0
tf.print(tf.shape(mammal))   #[]

#rank 1  张量
mystr = tf.Variable(["Hello"], tf.string)   #1阶,字符类型,列表
tf.print(tf.rank(mystr))    #1
tf.print(tf.shape(mystr))   #[1]

#rank 2  张量
mymat = tf.Variable([[7],[11]], tf.int16)   #0阶,字符类型,字符串
tf.print(tf.rank(mymat))    #2    元素个数
tf.print(tf.shape(mymat))   #[2 1]  相当于几行几列
#创建张量
tf.constant([1,2,3], dtype=tf.int16)   #<tf.Tensor: shape=(3,), dtype=int16, numpy=array([1, 2, 3], dtype=int16)>

tf.zeros((2,2),dtype=tf.int16)  
'''张量行列,数据类型,数据元素,
<tf.Tensor: shape=(2, 2), dtype=int16, numpy=
array([[0, 0],
       [0, 0]], dtype=int16)>
       
tf.reduce_sum(a,axis=1)   按照某一列或者某一行进行相加或相减
a.get_shape()  查看维度
tf.reshape(a,(1,4))   进行维度变换,有2*2变成1*4
b*5+1   数学运算
tf.matmul(a,b)   
a[0,0];a[:,0];a[0,:]  进行索引
'''
#reshape
rank_three_tensor=tf.ones([3,4,5])
matrix=tf.reshape(rank_three_tensor,[6,10])   #三维到二维
#tf.strings
#字符切割
tf.strings.bytes_split('hello')   #<tf.Tensor: shape=(5,), dtype=string, numpy=array([b'h', b'e', b'l', b'l', b'o'], dtype=object)>
help(tf.strings.split)   #官方帮助文档,有栗子
#单词切割  默认以空格为切割
tf.strings.split('hello world')   #<tf.Tensor: shape=(2,), dtype=string, numpy=array([b'hello', b'world'], dtype=object)>
#string hash  哈希算法,转化为数数字
tf.strings.to_hash_bucket(['hello','world'], num_buckets=10)  #<tf.Tensor: shape=(2,), dtype=int64, numpy=array([8, 1], dtype=int64)>
#tf.debugging  tf自带debug函数
a=tf.random.uniform((10,10))
tf.debugging.assert_equal(x=a.shape,y=(10,10))   #判断维数是否一致,没问题则继续往下执行
tf.debugging.assert_equal(x=a.shape,y=(10,20))   #出现错误则报错
import tensorflow as tf
a = tf.random.uniform(shape=(10,5),minval=0,maxval=10)   #随机函数
a
'''
<tf.Tensor: shape=(10, 5), dtype=float32, numpy=
array([[9.961878  , 1.8470013 , 3.929838  , 2.2912729 , 1.7339933 ],
       [6.4265766 , 9.381182  , 8.765488  , 1.6121304 , 8.999815  ],
       [9.099529  , 4.8890615 , 1.3474286 , 8.258262  , 3.9083278 ],
       [6.2407184 , 8.197422  , 5.0943146 , 0.28501272, 4.248129  ],
       [7.84971   , 4.96622   , 7.757106  , 1.4310932 , 3.4755325 ],
       [6.9145956 , 4.892148  , 2.954824  , 8.441023  , 2.7998877 ],
       [2.1173346 , 2.9841232 , 7.594227  , 3.4011757 , 5.2331567 ],
       [0.66922545, 9.514647  , 8.365441  , 8.474672  , 5.8095217 ],
       [1.0047925 , 8.470211  , 2.2050738 , 5.8963385 , 0.50420165],
       [6.1093483 , 5.8107843 , 6.2560916 , 1.5023386 , 7.7845097 ]],
      dtype=float32)>
'''
a = tf.constant([[1,2],[3,4]])   #初始化2个2*2的张量
b = tf.constant([[5,6],[7,8]])

tf.print(tf.math.add(a,b))      #加减乘除
tf.print(tf.math.subtract(a,b))
tf.print(tf.math.multiply(a,b))
tf.print(tf.math.divide(a,b))
'''
[[6 8]
 [10 12]]
[[-4 -4]
 [-4 -4]]
[[5 12]
 [21 32]]
[[0.2 0.33333333333333331]
 [0.42857142857142855 0.5]]
'''
x = tf.constant([1.8,2.2],dtype=tf.float32)   #创建一维张量
x1 = tf.dtypes.cast(x,tf.int32)               #将浮点数据转化为整形数据
x1
#<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 2])>

常用层

  • tf.keras.layers
  • tf.nn
    在大多数情况下,可以使用Tensorflow封装的tf.keras.layers构建一些层建模,keras层非常有用
    包括Dense,Conv2D,LSTM,BachNormalization,Dropout等。
    tf.nn:底层的函数库,tf.keras.layers是基于tf.nn的高度封装。
#文本分类
a = tf.random.nuiform(shape=(10,100,50),minval=-0.5,maxval=0.5)   #张量
x = tf.keras.layers.LSTM(100)(a)  #LSTM
x = tf.keras.layers.Dense(10)(x)  #全连接层
x = tf.nn.softmax(x)  #激活函数
三种建模方式
  • Sequential model(顺序模型)
#第一种Sequential model
from tensorflow.keras import layers
model = tf.keras.Sequential()
model.add(layers.Dense(64, activation='relu'))  #第一层
model.add(layers.Dense(64, activation='relu'))  #第二层
model.add(layers.Dense(10))   #第三层
#。。。。。
#第二种Sequential model
model = tf.keras.Seqential([
    layers.Dense(64, activation='relu', input_shape=(32,)),  #第一层
    layers.Dense(64, activation='relu'),  #第二层
    layers.Dense(10)   #第三层    
])
#添加损失函数等
model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
             loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
             metrics=['accuracy'])
import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000,10))
model.fit(data,labels,epochs=10,batch_size=32)
'''
tf.keras.Model.fit(用于训练模型)
 - epochs:训练分为几个时期。每一个epoch是对整个输入数据的一次迭代(此操作以较小的批次完成)。
 - batch_size:当传递NumPy数据时,模型将数据切成较小的批次,并在训练期间对这些批次进行迭代。该整数指定每个批次的大小。请注意,如果不能将样本总数除以批次大小,则最后一批可能会更小。
 - validation_data:在模型训练时,监控在某些验证数据上监视其性能。传递此参数(输入和标签的元组)可以使模型在每个时期结束时以推断模式显示所传递数据的损失和度量。
'''
  • Functional model(函数模型)
    函数式模型是一种创建模型的方法,该模型比tf.keras.Sequential更灵活。函数式模型可以处理具有非线性拓扑的模型,具有共享层的模型以及具有更多个输入或输出的模型等等
    深度学习模型通常都是层的有向无环图(DAG)的主要塑像。因此,函数式模型是一种构建层图的方法。
inputs = tf.keras.Input(shape=(32,))  #输入
#input = tf.keras.Inout(shape=(32,))  #可进行多个输入
x = layers.Dense(64, activation='relu')(inputs)  #第一层
x = layers.Dense(64, activation='relu')(x)  #第二层
predictions = layers.Dense(10)(x)  #第三层
model = tf.keras.Model(inputs=inputs,outputs=predictions)  #定义输入和输出
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),  #定义一个优化器
             loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),   #定义一个损失函数
             metrics=['accuracy'])   #定义一个评估函数

import numpy as np
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit(data, labels, batch_size=32, epochs=5)
inputs1 = tf.keras.Input(shape=(32,))  #输入
inputs2 = tf.keras.Input(shape=(32,))  #可进行多个输入
x1 = layers.Dense(64, activation='relu')(inputs1)  #第一层
x2 = layers.Dense(64, activation='relu')(inputs2)  #第一层
x = tf.concat([x1,x2],axis=-1)  
x = layers.Dense(64, activation='relu')(x)  #第二层
predictions = layers.Dense(10)(x)  #第三层

model = tf.keras.Model(inputs=[inputs1,inputs2],outputs=predictions)  #定义输入和输出
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),  #定义一个优化器
             loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),   #定义一个损失函数
             metrics=['accuracy'])   #定义一个评估函数

import numpy as np
data1 = np.random.random((1000, 32))
data2 = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit((data1,data2), labels, batch_size=32, epochs=5)
  • Subclassing model(子类化模型)
    通过子类化tf.keras.Model和定义自己的前向传播模型来构建完全可定制的模型。
    和eager execution模式相辅相成。
#定义一个子类化模型
from tensorflow.keras import layers
import tensorflow as tf
class MyModel(tf.keras.Model):
    
    def __init__(self, num_classes=10):
        super(MyModel, self).__init__(name='my_model')
        self.num_classes = num_classes
        #定义自己需要的层
        self.dense_1 = layers.Dense(32, activation='relu')
        self.dense_2 = layers.Dense(num_classes)
        
    def call(self, inputs):
        #定义前向传播
        #使用在(in __init__)定义的层
        x = self.dense_1(inputs)
        return self.dense_2(x)
model = MyModel(num_classes=10)

model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
             loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
             metrics=['accuracy'])

import numpy as np

data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
model.fit(data, labels, batch_size=32, epochs=5)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值