用Tensorflow實現多層神經網絡


用Tensorflow實現簡單多層神經網絡

覺得有用的話,歡迎一起討論相互學習~

我的微博我的github我的B站

參考文獻
Tensorflow機器學習實戰指南

源代碼見下方鏈接

ReLU激活函數/L1范數版本

Sigmoid激活函數/交叉熵函數版本

數據集及網絡結構

數據集

  • 使用預測出生體重的數據集csv格式,其中數據的第2列至第8列為訓練屬性,第9列為體重數據即標簽,第一列為標記是否為低出生體重的標記,本博文中不對其進行討論。

Low Birthrate data:

Columns(列)   Variable(值)                             Abbreviation
-----------------------------------------------------------------------------
Low Birth Weight (0 = Birth Weight >= 2500g,            LOW
                         1 = Birth Weight < 2500g)
低出生體重
Age of the Mother in Years                              AGE
母親妊娠年齡
Weight in Pounds at the Last Menstrual Period           LWT
在最后一次月經期間體重增加。
Race (1 = White, 2 = Black, 3 = Other)                  RACE
膚色
Smoking Status During Pregnancy (1 = Yes, 0 = No)       SMOKE
懷孕期間吸煙狀態
History of Premature Labor (0 = None  1 = One, etc.)    PTL
早產的歷史
History of Hypertension (1 = Yes, 0 = No)               HT
高血壓歷史
Presence of Uterine Irritability (1 = Yes, 0 = No)      UI
子宮刺激性的存在
Birth Weight in Grams                                   BWT
以克為單位的體重

網絡結構

  • 所使用網絡結構十分簡單為三層隱層網絡分別為25-10-3 的結構。其中loss 函數為L1損失范數,激活函數為ReLU.

少說廢話多寫代碼

數據讀取

import tensorflow as tf
import matplotlib.pyplot as plt
import csv
import os
import numpy as np
import requests
from tensorflow.python.framework import ops

# name of data file
# 數據集名稱
birth_weight_file = 'birth_weight.csv'

# download data and create data file if file does not exist in current directory
# 如果當前文件夾下沒有birth_weight.csv數據集則下載dat文件並生成csv文件
if not os.path.exists(birth_weight_file):
    birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introduction/07_Working_with_Data_Sources/birthweight_data/birthweight.dat'
    birth_file = requests.get(birthdata_url)
    birth_data = birth_file.text.split('\r\n')
    # split分割函數,以一行作為分割函數,windows中換行符號為'\r\n',每一行后面都有一個'\r\n'符號。
    birth_header = birth_data[0].split('\t')
    # 每一列的標題,標在第一行,即是birth_data的第一個數據。並使用制表符作為划分。
    birth_data = [[float(x) for x in y.split('\t') if len(x) >= 1] for y in birth_data[1:] if len(y) >= 1]
    # 數組第一維表示遍歷行從第一行開始,所以不包含標題,數組第二維遍歷列(使用制表符進行分割)
    # print(np.array(birth_data).shape)
    # (189, 9)不包含標題
    # 此為list數據形式不是numpy數組不能使用np,shape函數,但是我們可以使用np.array函數將list對象轉化為numpy數組后使用shape屬性進行查看。
    # 注意,向其中寫入文件時一定要去掉換行等操作符號,如果在csv中有換行符,也會作為一行數據的。
    # 讀文件時,我們把csv文件讀入列表中,寫文件時會把列表中的元素寫入到csv文件中。
    #
    # list = ['1', '2', '3', '4']
    # out = open(outfile, 'w')
    # csv_writer = csv.writer(out)
    # csv_writer.writerow(list)
    # 可能遇到的問題:直接使用這種寫法會導致文件每一行后面會多一個空行。
    #
    # 解決辦法如下:
    #
    # out = open(outfile, 'w', newline='')  注意newline屬性
    # csv_writer = csv.writer(out, dialect='excel')
    # csv_writer.writerow(list)

    with open(birth_weight_file, "w", newline='') as f:
        # 創建當前目錄下birth_weight.csv文件
        writer = csv.writer(f)
        writer.writerows([birth_header])
        writer.writerows(birth_data)
        f.close()

# 將出生體重數據讀進內存
birth_data = []
with open(birth_weight_file, newline='') as csvfile:
    csv_reader = csv.reader(csvfile)  # 使用csv.reader讀取csvfile中的文件
    birth_header = next(csv_reader)  # 讀取第一行每一列的標題
    for row in csv_reader:  # 將csv 文件中的數據保存到birth_data中
        birth_data.append(row)

birth_data = [[float(x) for x in row] for row in birth_data]  # 將數據轉換為float格式

# 對於每組數據而言,第8列(序號從0開始)即為標簽序列-體重
y_vals = np.array([x[8] for x in birth_data])

# 特征序列
cols_of_interest = ['AGE', 'LWT', 'RACE', 'SMOKE', 'PTL', 'HT', 'UI']
x_vals = np.array(
    [[x[ix] for ix, feature in enumerate(birth_header) if feature in cols_of_interest] for x in birth_data])
# 數組一維使用for x in birth_data遍歷整個數組
# enumerate(birth_header)函數返回ix索引和feature特征,用讀取的feature和cols_of_interest進行匹配
# 使x[ix]數據存入數組中

數據預處理

# 重置Tensorflow圖模型
ops.reset_default_graph()

# Create graph session
sess = tf.Session()

# set batch size for training
batch_size = 100

# make results reproducible
seed = 3
np.random.seed(seed)
tf.set_random_seed(seed)

# 將所有數據分割成訓練集80%測試集20%
train_indices = np.random.choice(len(x_vals), round(len(x_vals)*0.8), replace=False)
# np.random.choice(a,n,p)可以傳入一個一維數組a或者一個int值a,如果是一維數組a將可以設定幾率P返回數組中的n個值。
# 如果是int值a,則返回一個隨機生成0~(a-1)之間的n個數的數組。利用該數組可以作為數據的索引值來選定數據集中一定比例的樣本。
'''
 Examples
            Generate a uniform random sample from np.arange(5) of size 3:
            >>> np.random.choice(5, 3)
            array([0, 3, 4])
            >>> #This is equivalent to np.random.randint(0,5,3)

            Generate a non-uniform random sample from np.arange(5) of size 3:
            >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
            >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
            array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
                  dtype='|S11')
'''
test_indices = np.array(list(set(range(len(x_vals))) - set(train_indices)))
'''example
------------------------------
a = range(8)
print('a:', a)
b = set(a)
print('b=set(a):', b)
a1 = np.array([1, 4, 6])
print('a1=np.array:', a1)
b1 = set(a1)
print('b1=set(a1):', b1)
c = list(b - b1)
print('list(b-b1)', c)
# a: range(0, 8)
# b=set(a): {0, 1, 2, 3, 4, 5, 6, 7}
# a1=np.array: [1 4 6]
# b1=set(a1): {1, 4, 6}
# list(b-b1) [0, 2, 3, 5, 7]

'''
x_vals_train = x_vals[train_indices]
x_vals_test = x_vals[test_indices]
y_vals_train = y_vals[train_indices]
y_vals_test = y_vals[test_indices]


# 標准化操作,將數據標准化到0~1的區間
def normalize_cols(m):
    col_max = m.max(axis=0)
    col_min = m.min(axis=0)
    return (m - col_min)/(col_max - col_min)


x_vals_train = np.nan_to_num(normalize_cols(x_vals_train))
x_vals_test = np.nan_to_num(normalize_cols(x_vals_test))


# 解決NaN無法處理的問題,如果是很大的(正/負)數用一個很大的(正/負)實數代替,如果是很小的數用0代替

構建神經網絡模型

# 定義變量函數(權重和偏差),stdev參數表示方差
def init_weight(shape, st_dev):
    weight = tf.Variable(tf.random_normal(shape, stddev=st_dev))
    return (weight)


def init_bias(shape, st_dev):
    bias = tf.Variable(tf.random_normal(shape, stddev=st_dev))
    return (bias)


# 創建數據占位符
x_data = tf.placeholder(shape=[None, 7], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)


# 創建一個全連接層函數
def fully_connected(input_layer, weights, biases):
    layer = tf.add(tf.matmul(input_layer, weights), biases)
    return (tf.nn.relu(layer))


# --------Create the first layer (25 hidden nodes)--------
weight_1 = init_weight(shape=[7, 25], st_dev=10.0)
bias_1 = init_bias(shape=[25], st_dev=10.0)
layer_1 = fully_connected(x_data, weight_1, bias_1)

# --------Create second layer (10 hidden nodes)--------
weight_2 = init_weight(shape=[25, 10], st_dev=10.0)
bias_2 = init_bias(shape=[10], st_dev=10.0)
layer_2 = fully_connected(layer_1, weight_2, bias_2)

# --------Create third layer (3 hidden nodes)--------
weight_3 = init_weight(shape=[10, 3], st_dev=10.0)
bias_3 = init_bias(shape=[3], st_dev=10.0)
layer_3 = fully_connected(layer_2, weight_3, bias_3)

# --------Create output layer (1 output value)--------
weight_4 = init_weight(shape=[3, 1], st_dev=10.0)
bias_4 = init_bias(shape=[1], st_dev=10.0)
final_output = fully_connected(layer_3, weight_4, bias_4)

# 絕對值L1損失范數
loss = tf.reduce_mean(tf.abs(y_target - final_output))

# 定義優化器
my_opt = tf.train.AdamOptimizer(0.01)  # 使用Adam優化器,學習率使用0.01
train_step = my_opt.minimize(loss)

填充數據與訓練

# Initialize Variables
init = tf.global_variables_initializer()
sess.run(init)

# 訓練
loss_vec = []
test_loss = []
for i in range(2000):
    rand_index = np.random.choice(len(x_vals_train), size=batch_size)
    rand_x = x_vals_train[rand_index]  # shape=[batch_size,7]
    rand_y = y_vals_train[rand_index].reshape([batch_size, 1])
    # 使用訓練數據對網絡進行訓練
    sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})

    temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
    loss_vec.append(temp_loss)  # 將訓練集上的誤差存進loss_vec中

    test_temp_loss = sess.run(loss, feed_dict={x_data: x_vals_test, y_target: np.transpose([y_vals_test])})
    test_loss.append(test_temp_loss)  # 將測試集上的誤差存進test_loss中
    if (i + 1)%200 == 0:
        print('Generation: ' + str(i + 1) + '. Loss = ' + str(temp_loss))



# 結果展示
Generation: 200. Loss = 2763.73
Generation: 400. Loss = 1717.1
Generation: 600. Loss = 1218.89
Generation: 800. Loss = 1493.56
Generation: 1000. Loss = 1634.2
Generation: 1200. Loss = 1392.12
Generation: 1400. Loss = 1388.24
Generation: 1600. Loss = 1055.66
Generation: 1800. Loss = 1105.95
Generation: 2000. Loss = 1205.54

使用matplotlib繪制loss值

# 使用matplotlib顯示loss
plt.plot(loss_vec, 'k-', label='Train Loss')
plt.plot(test_loss, 'r--', label='Test Loss')
plt.title('Loss (MSE) per Generation')
plt.legend(loc='upper right')
plt.xlabel('Generation')
plt.ylabel('Loss')
plt.show()

升級版本

使用sigmoid激活函數交叉熵函數作為Cost Function

  • 只需做如下修改
# activation 標志位Ture則使用非線性函數sigmoid,否則使用線性函數方式
def logistic(input_layer, multiplication_weight, bias_weight, activation=True):
    linear_layer = tf.add(tf.matmul(input_layer, multiplication_weight), bias_weight)
    if activation:
        return (tf.nn.sigmoid(linear_layer))
    else:
        return (linear_layer)

# 交叉熵函數
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=final_output, labels=y_target))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM