tensorflow2

目录

构建线性模型

常量

基础数学计算

变量

初始化模型

构建损失函数

模型训练及可视化

Keras

mnist手写数字识别

数据读取及探索

交叉熵

模型构建及训练

调用保存好的模型预测样本


机器学习平台

  1. TensorFlow:谷歌,Python、JavaScript、C++、Java,Linux、Windows、Mac OS X、Andriod、ios

  2. Caffe: 加州大学,C++、Python、Matlab,Linux、Windows、Mac Os x

  3. PyTorch: facebook

  4. PaddlePaddle:百度

构建线性模型

常量

a = tf.constant([1,2])
b = tf.constant([3,4])
a + b
out:<tf.tensor:shape=(2,) ,dtype=int32,numpy=array([4,6])>

tensorflow1不会返回运算的值

res = a + b
res.numpy()#访问元素操作

基础数学计算

如果a=[1,2]

对a求均值返回的值为1

因为a的数据类型是32位的整形

如果想得到浮点型的结果,则定义为浮点型

a = tf.constant([1.0,2])
b = tf.constant([3,4])

a和b数据类型不同进行共同处理则会报错

tensorflow比numpy方便且高效

变量

a = tf.Variable(2.0)
​
Out: <tf. Variable: shape=( )dtype=float32, numpy=2.0>

初始化模型

 

# 读取数据
data = pd.read_csv('line_fit_data.csv').values#取数据框内的具体值,最终取到的是二维数组
x = data[:, 0]#所有行的第一列
target_y = data[:, 1]


# 构造一个线性模型:𝑦=𝑤𝑥+𝑏,在训练过程中w和b不断进行修正
w = tf.Variable(-10.0)
b = tf.Variable(7.0)#随机给w和b赋值
​
def model(x, w, b):
    return w*x + b #实现线性模型

构建损失函数

#损失函数衡量实际值和预测值的差异
def loss(predicted_y, target_y):   # 构造损失函数
    return tf.reduce_mean(tf.square(predicted_y-target_y))#均方误差
​

模型训练及可视化

 

for i in range(100):
    print('第', i, ' 轮训练的损失值:', loss(model(x, w, b), target_y).numpy(), 'w=', w.numpy(), 'b=', b.numpy())
    with tf.GradientTape() as t:
        dw, db = t.gradient(loss(model(x, w, b), target_y), [w, b])#梯度下降
    w.assign_sub(learning_rate*dw)  # 反向寻优更新模型的参数
    b.assign_sub(learning_rate*db)


plt.figure(figsize=(10, 5))#画布大小
plt.axis([-0.01, 1, -3, 10])#坐标范围
plt.scatter(x, target_y)#样本实际值
plt.plot(x, model(x, w, b).numpy(), color='red')#模型预测值
plt.legend(['predicted_y', 'target_y'])
​

Keras

keras在tensorflow1中作为独立的库使用

使用tf.keras高级API训练神经网络模型

model = tf.keras.Sequential()#实例化,线性堆叠的网络图层
model.add(tf.keras.layers.Dense(1, input_shape=(1,)))#添加一层全连接层
model.compile(loss='mse',optimizer=tf.keras.optimizers.SGD(learning_rate=0.7))#编译模型. 
model.fit(x, target_y, verbose=2, epochs=20, validation_split=0.2)#模型训练与验证

 
# 使用tf.keras高级API训练神经网络模型
​
# 搭建模型(网络)
model_net = tf.keras.models.Sequential()# 实例化一个网络模型
model_net.add(tf.keras.layers.Dense(1, input_shape=(1, )))   # 为网络添加一个全连接层
model_net.compile(loss='mse',optimizer=tf.keras.optimizers.SGD(learning_rate=0.5))  # 模型编译
#mse均方误差,优化器SGD梯度下降
# 模型训练
model_net.fit(x, target_y, verbose=1, epochs=20, validation_split=0.2)

 

mnist手写数字识别

数据读取及探索

tensorflow2和tensorflow1对比

  • tensorflow1:定义计算与执行计算分开

  • tensorflow2: Eager模式, 实时执行

 

MNIST数据集包括6000个0~9的手写数字图像,每张图像包括784个像素值及一个标签。

 

目标:构建模型,识别图像的数字

 

加入特征转换过程

 

# 读取数据
data = np.load('mnist.npz')
data.files#查看具体数据集
train_images, train_labels, test_images, test_labels = data['x_train'], data['y_train'], data['x_test'], data['y_test']

交叉熵

网络结构

神经网络模型

 

输入层传入的是一维的向量,所以对二维图片(28*28的数组)进行fasten拉伸处理

 输出层有十个类别

 y‘样本实际值 y为样本预测值

target_y = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])#预测值为0
predicted_y1 = np.array([0.4, 0.5, 0.1, 0, 0, 0, 0, 0, 0, 0])#实际值为1
predicted_y2 = np.array([0.1, 0.2, 0.7, 0, 0, 0, 0, 0, 0, 0])#实际值为2
-np.sum(target_y*np.log(predicted_y1+0.0000001))#为了防止出现对0取对数,加一个很小的数
-np.sum(target_y*np.log(predicted_y2+0.0000001))
​
>>Out[1]:0.9162904818741863
>>Out[2]:2.302584092994546
#predicted_y1更接近预测值

模型构建及训练

搭建网络

model = tf.keras.models.Sequential()#实例化
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))#将图片拉伸
model.add(tf.keras.layers.Dense(128, activation='relu'))#隐藏层有128个神经元,激活函数是relu
model.add(tf.keras.layers.Dense(10, activation='softmax'))#输出层十个神经元,激活函数用的softmax

编译模型

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy', metrics=['accuracy'])#adam优化器,矢量优化器,在梯度优化算法上做了改进,损失函数用的交叉熵,评估输出用accuracy(精度:模型预测正确的个数在所有预测中占的比例)
model.fit(train_images, train_labels, verbose=1, epochs=20, validation_data=(test_images, test_labels))

调用保存好的模型预测样本

model.save('model_mnist.h5')  # 保存模型
model=tf.keras.models.load_model('model_mnist.h5')  # 加载模型
model.summary()   # 查看模型基本信息


for i in range(30):
    image = plt.imread('testimages/'+str(i)+'.jpg')#读取照片
    image_new = image.reshape([1, 28, 28])#对照片进行维度转化
    result = model.predict(image_new)[0].argmax() #输出预测结果
    print('第', i, ' 张照片中的数字是:', result)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值