tensorflow2.0建立神經網路模型,tensorflow近似求導與keras.optimizers結合使用,實現自定義求導,使得模型訓練更加靈活。tensorflow2.0學習筆記:應用tensorflow近似求導介紹tensorflow求導的基本用法。
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras
print
(tf.__version__)
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(
)
from sklearn.model_selection import train_test_split
x_train_all, x_test, y_train_all, y_test = train_test_split(
housing.data, housing.target, random_state =7)
x_train, x_valid, y_train, y_valid,
= train_test_split(
x_train_all, y_train_all, random_state =11)
print
(x_train.shape, y_train.shape)
print
(x_valid.shape, y_valid.shape)
print
(x_test.shape, y_test.shape)
from sklearn.preprocessing import standardscaler
scaler = standardscaler(
)x_train_scaled = scaler.fit_transform(x_train)
x_valid_scaled = scaler.transform(x_valid)
x_test_scaked = scaler.transform(x_test)
# metric 使用
# 輸入的是兩個列表
# 累加資料特性,具有累加功能
metric = keras.metrics.meansquarederror(
)# meansquarederror:差的平方的均值
print
(metric([5
.],[
2.])
)# (5-2)*2 = 9
print
(metric([0
.],[
1.])
)# (0-1)*2 = 1
print
(metric.result())
# (9+1)/2 = 5
metric.reset_states(
)# 清空metric之前記錄的結果
metric([1
.],[
3.])
print
(metric.result(
))
#fit 函式做了什麼?
# 1. 按照 batch 遍歷訓練集,記錄metric
# 1.1 自動求導
# 2.epoch 結束 驗證集 記錄metric
epochs =
10batch_size =
32step_per_epoch =
len(x_train_scaled)
//batch_size #整除batch_size
# 隨機取32個資料,隨機取32個索引
defrandom_batch
(x,y,batch_size =32)
: idx = np.random.randint(0,
len(x)
,size = batch_size)
x_idx= tf.cast(x[idx]
,dtype=tf.float32)
# 取對應索引的資料
y_idx= tf.cast(y[idx]
,dtype=tf.float32)
return x_idx,y_idx
#建立模型
model = keras.models.sequential(
[ keras.layers.dense(
30, activation=
'relu'
, input_shape=x_train.shape[1:
]), keras.layers.dense(1)
,])
自定義求導optimizer = keras.optimizers.sgd(
)metric = keras.metrics.meansquarederror(
)for epoch in
range
(epochs)
:#遍歷epochs
metric.reset_states(
)# set metric
for step in
range
(step_per_epoch)
: x_batch,y_batch = random_batch(x_train_scaled,y_train,batch_size)
# 取資料,batch_size個
with tf.gradienttape(
)as tape:
y_pred = model(x_batch)
loss = tf.reduce_mean(keras.losses.mean_squared_error(y_batch,y_pred)
) metric(y_batch,y_pred)
#累計計算metric
grads = tape.gradient(loss,model.variables)
# 求梯度
grads_and_vars =
zip(grads,model.variables)
# 多個變數,需要通過zip繫結
# 梯度更新
print
('\repoch'
,epoch,
'train mse:'
,metric.result(
).numpy(
),end='')
y_valid_pred = model(x_valid_scaled)
#驗證集驗證
valid_loss = tf.reduce_mean(keras.losses.mean_squared_error(y_valid_pred,y_valid)
)print
('\t'
,'valid mse: '
,valid_loss.numpy(
))
tensorflow2 0學習筆記(3 2)
自編碼器變種 1 denoising auto encoder 加隨機雜訊 2 dropout auto encoder 防止過擬合 3 adversarial auto encoder 利用額外的判別器網路來判定降維的隱藏變數?是否取樣先驗分布?對抗自編碼器是從下一章要介紹的生成對抗網路演算法衍生...
Tensorflow2 0學習筆記 建立張量
使用constant建立張量 使用constant函式建立張量 其中 1,5 表示張量內容,dtype表示資料型別 a tf.constant 1,5 dtype tf.int32 輸出a,a的資料型別,a的形狀 print a print a.dtype print a.shape 輸出結果 tf...
Tensorflow2 0學習筆記 常用函式(一)
1.資料型別轉換函式 定義乙個張量 a tf.constant 0,1,2 3,4,5 6,7,8 dtype tf.int64 強制轉換型別函式 b tf.cast a,tf.float32 reduce max查詢張量中最大的數,axis x表示對對應的行或者列求和 本例中為二維張量,0對應的對...