Tensorflow 回歸與分類

Tensorflow 回歸與分類

1.1 Tensorflow是什么?

Tensorflow是谷歌公司推出的開源深度學(xué)習框架,利用它我們可以快速搭建深度學(xué)習模型。

1.2 Tensorflow是什么樣的框架?

Tensorflow跟很多機器學(xué)習庫類似,采用了“流圖”方式,這樣做的好處可以減小計算開銷。一般情況下,python的數(shù)值計算庫會將矩陣乘法之類的復(fù)雜計算傳送到外部外部語言計算(更高效的語言c,匯編等),但是每次計算轉(zhuǎn)換回來的操作依然是很大的開銷。所以“流圖”方式采用,先用圖和流來描述模型,再將整個模型一起送出去計算,計算完再送回來,這樣減少了轉(zhuǎn)換次數(shù)以減少開銷。

1.3 Tensorflow怎么用?

Tensorflow內(nèi)部集成了很多的神經(jīng)網(wǎng)絡(luò)的反向傳播算法,以及其優(yōu)化方式。只需要編程設(shè)置相應(yīng)的參數(shù)即可選擇適當?shù)姆聪騻鞑?yōu)化器。

它為我們解決了復(fù)雜的反向傳播過程的實現(xiàn),在構(gòu)建模型時,我們只需要搭建正向的神經(jīng)網(wǎng)絡(luò)傳輸模型以及給出損失函數(shù)即可。

1.4 再具體一點?

在Tensorflow中操作的數(shù)據(jù)對象是tensor(包括常量和變量),由對象和操作OP就構(gòu)成了圖Graph, 將各個圖的輸入輸出連接就形成的流圖,至此模型的表示便完成了。在這個框架下表示和執(zhí)行是分開的,因此,session會話便出場了,將表示放在session中就可以運行了。在運行中很可能要使用到變量,只有數(shù)據(jù)的更新,才能得到“活水流”,那么怎么在session中賦予新的數(shù)據(jù)或者獲取新數(shù)據(jù),使用 tf.placeholder() 創(chuàng)建占位符的op中可以使用 feed 賦值如:sess.run([output], feed_dict={input1:[7.], input2:[2.]}),可以使用 fetch來獲取操作的返回值(可以是多個)如: result = sess.run([mul, intermed])。result是多個值。

對于損失函數(shù)的構(gòu)建情況較多(常選擇的有均方差,信息熵等),反向優(yōu)化可以調(diào)用相應(yīng)的操作即可(常選擇梯度下降法),下面看一個完整的例子:

import tensorflow as tf

import numpy as np

#1, 數(shù)據(jù)準備

x_dat=np.float32(np.random.rand(2,100))

y_dat=np.dot([2.0,3.0],x_dat)+5.0

x = tf.placeholder(tf.float32)

y = tf.placeholder(tf.float32)

# 2,變量定義及模型構(gòu)建

W=tf.Variable(tf.random_uniform([1,2],-0.1,0.1))

b=tf.Variable(tf.zeros([1]))

y_pre=tf.matmul(W,x)+b

# 3,構(gòu)建損失函數(shù)及選擇優(yōu)化器

loss=tf.reduce_mean(tf.square(y_pre-y))

optim=tf.train.GradientDescentOptimizer(0.5)

train_op=optim.minimize(loss)

# 4,初始化變量啟動會話,訓(xùn)練

init=tf.initialize_all_variables()

sess=tf.Session()

sess.run(init)

for step in range(1,200):

? ? sess.run([train_op],feed_dict={x:x_dat,y:y_dat })

? ? if step%20 ==0 :

? ? ? ? print(sess.run([W,b]))

session在運行之前需要構(gòu)建整個圖,除了sesion之外,還有一個可以在圖運行中出入其他圖的會話InteractiveSession。


1.5多元線性回歸

下面是一個多元線性回歸的例子,將模型構(gòu)建函數(shù)抽抽離單獨實現(xiàn),在主程序中調(diào)用,可以使程序復(fù)用性更強。

敲黑板,劃重點:

Tip1: out = tf.matmul( w,inputs) + b #注意matmul的參數(shù)順序

Tip2: optmiz = tf.train.GradientDescentOptimizer(0.1) #不收斂需調(diào)整變化率,這里0.5不收斂,太小則訓(xùn)練太慢。

Tip3: train_op = optmiz.minimize(loss) #根據(jù)loss來確定改變變量的方向及數(shù)值

# 多元線性回歸

import tensorflow as tf

import numpy as np

# 模型構(gòu)建函數(shù)

def add_layer(inputs, insize, outsize, activation_fun=None):

? ? w = tf.Variable(tf.random_normal([outsize,insize]))

? ? b = tf.Variable(tf.zeros([outsize,1]))

? ? #print(inputs.shape)

? ? out = tf.matmul( w,inputs) + b #注意matmul的參數(shù)順序

? ? if activation_fun is None:

? ? ? ? output = out

? ? else:

? ? ? ? output = activation_fun(out)

? ? print(output.shape)

? ? return output,w,b

# 1,數(shù)據(jù)準備

x_dat = np.float32(np.random.rand(5,200))

y_dat = np.dot([2.0, 3.0, 2.0,4.0,9.0],x_dat)+5.0

x = tf.placeholder(tf.float32)

y = tf.placeholder(tf.float32)

# 2,模型構(gòu)建,變量定義

y_pre,w,b = add_layer(x, 5, 1, activation_fun=None)

# 3,構(gòu)建損失函數(shù)及選擇優(yōu)化器

loss = tf.reduce_mean(tf.square(y-y_pre))

#loss = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pre),reduction_indices=[1]))

optmiz = tf.train.GradientDescentOptimizer(0.1)? #不收斂需調(diào)整變化率,這里0.5不收斂,太小則訓(xùn)練太慢。

train_op = optmiz.minimize(loss) #根據(jù)loss來確定改變變量的方向及數(shù)值

# 4,啟動會話,初始化變量,訓(xùn)練

init = tf.global_variables_initializer()

with tf.Session() as sess:

? ? sess.run(init)

? ? for step in range(2000):

? ? ? ? sess.run([train_op],feed_dict={x: x_dat, y: y_dat})

? ? ? ? if step % 200 == 0:

? ? ? ? ? ? print(sess.run([loss,w,b],feed_dict={x: x_dat, y: y_dat}))

結(jié)果如下:

1.6分類的例子:

# 分類

import tensorflow as tf

import numpy as np

import random

# AX=0 相當于matlab中 null(a','r')

def null(a, rtol=1e-5):

? ? u, s, v = np.linalg.svd(a)

? ? rank = (s > rtol * s[0]).sum()

? ? return rank, v[rank:].T.copy()

# 符號函數(shù),之后要進行向量化

def sign(x):

? ? if x > 0:

? ? ? ? return 1

? ? elif x == 0:

? ? ? ? return 0

? ? elif x < 0:

? ? ? ? return -1

# noisy=False,那么就會生成N的dim維的線性可分數(shù)據(jù)X,標簽為y

# noisy=True, 那么生成的數(shù)據(jù)是線性不可分的,標簽為y

def mk_data(N, noisy=False):

? ? rang = [-1, 1]

? ? dim = 5

? ? X = np.random.rand(dim, N) * (rang[1] - rang[0]) + rang[0]

? ? while True:

? ? ? ? Xsample = np.concatenate((np.ones((1, dim)), np.random.rand(dim, dim) * (rang[1] - rang[0]) + rang[0]))

? ? ? ? k, w = null(Xsample.T)

? ? ? ? y = sign(np.dot(w.T, np.concatenate((np.ones((1, N)), X))))

? ? ? ? print(y[0][5])

? ? ? ? if np.all(y):

? ? ? ? ? ? break

? ? day=[]

? ? if noisy == True:

? ? ? ? idx = random.sample(range(1, N), N / 10)

? ? ? ? y[idx] = -y[idx]

? ? for st in range(200):

? ? ? ? if(y[0][st]==1):

? ? ? ? ? ? y1 = [1,0]

? ? ? ? else:

? ? ? ? ? ? y1 = [0,1]

? ? ? ? day.append(y1)

? ? da_x = np.float32(X.transpose())

? ? da_y = np.float32(day)

? ? return da_x, da_y, w

# 模型構(gòu)建函數(shù)

def add_layer(insize, outsize, input, function = None):

? ? weight = tf.Variable(tf.random_normal([insize,outsize]))

? ? basize = tf.Variable(tf.zeros([outsize]))

? ? out = tf.matmul(input, weight) + basize

? ? if(function == None):

? ? ? ? output = out

? ? else:

? ? ? ? output = function(out)

? ? return output

# 1,數(shù)據(jù)準備

#產(chǎn)生的數(shù)據(jù)為隨機數(shù)據(jù),訓(xùn)練結(jié)果可能會不穩(wěn)定

sign = np.vectorize(sign)

x_dat, y_dat, w = mk_data(200)

#x_dat = np.float32(np.random.rand(200,5)*5+10)

#y_dat = np.float32(np.zeros([200,2]))

# x_dat2 = np.float32(np.random.rand(200,5))

# y_dat2 = np.float32(np.zeros([200,2])+1)

x = tf.placeholder(tf.float32)

y = tf.placeholder(tf.float32)

print(x_dat.shape)

print(y_dat.shape)

# 2,模型構(gòu)建,變量定義

y_pre = add_layer(5,2,x,tf.nn.softmax)

# 3,構(gòu)建損失函數(shù)及選擇優(yōu)化器

loss = -tf.reduce_sum(y*tf.log(y_pre))

optim = tf.train.GradientDescentOptimizer(0.05)

train_op = optim.minimize(loss)

accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_pre),tf.argmax(y)),tf.float32))

# 4,啟動會話,初始化變量,訓(xùn)練

init = tf.global_variables_initializer()

with tf.Session() as sess:

? ? sess.run(init)

? ? for step in range(2000):

? ? ? ? sess.run([train_op],feed_dict={x:x_dat,y:y_dat})

? ? ? ? if step % 100 == 0 :

? ? ? ? ? ? print(sess.run([loss,accuracy],feed_dict={x:x_dat,y:y_dat}))

? ? ? ? ? ? print(accuracy.eval(feed_dict={x:x_dat,y:y_dat}))


————————————————

版權(quán)聲明:本文為CSDN博主「AI小白龍」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。

原文鏈接:https://blog.csdn.net/qq_34106574/article/details/94406204

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容