總說
tensorflow最近很火啊,更新也超級快。以前學(xué)了matconvnet的,但是后來要做的東西卻是torch框架的,當(dāng)學(xué)習(xí)torch時,感覺這框架真是令人耳目一新。
Lua這是一門挺有趣的語言,反正寫著類似C和matlab的結(jié)合版本。主要是torch框架預(yù)先一層一層定義網(wǎng)絡(luò),然后對于自定義的網(wǎng)絡(luò)層,只需要重載3個函數(shù),主要是初始化函數(shù)、前向傳播函數(shù)以及反向傳播函數(shù)。代碼很簡潔。但是最令人頭大的一點是lua的調(diào)試IDE確實爛。主要是ZerobraneStudio,不想多說,反正不好。最關(guān)鍵的是torch沒有像matlab那么多的特別強大的函數(shù)庫啊。另外矩陣的賦值在一些情況下也沒有像matlab那么簡單,在矩陣像另一個矩陣進(jìn)行賦值的情況下,還要考慮賦值的矩陣空間是否連續(xù)。。媽呀,有點回到C的感覺了。不開心??聪旅娲a。。功能就是類似matlab的
reshape(mat, [1 size(mat)])
這個等價與tensorflow的矩陣處理函數(shù)expand_dim
expanded_vectors = tf.expand_dims(mat,0)
說一嘴啊,Python的數(shù)組是從0開始的,matlab是從1開始的,C/C++/Java/C#是從0開始的,Lua是從1開始的。你知道lua的上面的功能怎么寫嗎。。沒有對torch這個框架較為熟悉的人還真的寫不出。。
function torch.add_dummy(self)
local sz = self:size()
local new_sz = torch.Tensor(sz:size()+1)
new_sz[1] = 1
new_sz:narrow(1,2,sz:size()):copy(torch.Tensor{sz:totable()})
if self:isContiguous() then
return self:view(new_sz:long():storage())
else
return self:reshape(new_sz:long():storage())
end
end
這也是為什么現(xiàn)狀對torch不太感興趣的緣故吧,函數(shù)庫實在是有點少。
其實最主要的是只是初步學(xué)習(xí)了torch的緣故啊~哈哈。其實看torch代碼很舒服的,可以看看我的torch7專欄。
torch7
額,扯遠(yuǎn)了。話說tensorflow有那么好嗎?首先接觸tensorflow時我就醉了,官網(wǎng)上的文檔也太多了吧??!相比起來torch的文檔連其1/10都不到。不吹不黑啊。而且內(nèi)置的函數(shù)庫真是多到可以和matlab相匹敵的地步啊。果斷學(xué)習(xí)tensorflow啊。額額。直接看代碼快速入門吧。然后以后好好把官網(wǎng)上的文檔都看一下,記錄筆記吧。決定好好學(xué)一下tf咯。
第一課
#-- coding: UTF-8 --
'''
session的通用使用方法
'''
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.image as mlpimg
filename = '1.jpg'
raw_image = mlpimg.imread(filename)
image = tf.placeholder('uint8',[None, None, 3])
slice1 = tf.slice(image,[0,0,0],[1000,1000,-1])
slice2 = tf.slice(image,[1001,1001,0],[-1,-1,-1])
with tf.Session() as session:
y1 = session.run(slice1,feed_dict={image:raw_image})
y2 = session.run(slice2,feed_dict={image:raw_image})
#注意,如果要進(jìn)行顯示圖像,則必須先inshow(tensor)一下。
plt.imshow(y2)
plt.show()
print('OK!')
#解析placeholder
"""
在tensorflow中,就是先將各種操作定義好。比如即使是一個網(wǎng)絡(luò),不也是各種操作的集合嗎?
對于一些變量,運行時才統(tǒng)一賦予初值(喂入數(shù)據(jù)),這些變量除了簡單的constant,Variable之外
還有一般要用到placeholder。placeholder從字面意思上看就是占位符,和動態(tài)分配的list類似啊。
功能強大,可以設(shè)置該變量的類型,數(shù)據(jù)的維度之類的。比如tf.placeholder('uint8',[None,None,3])
就可以處理任何3個通道的圖片。
"""
#其他解析
"""
1. tf.slice(x,[start1,start2,...startn],[end1,end2,...endn])
2. 這里要牢牢記住的就是:先搭框架!搭好之后再統(tǒng)一喂入數(shù)據(jù)。比如
slice1 = tf.slice(image,[0,0,0],[1000,1000,-1])時候
"""
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
第二課
'''
這個是交互式session的使用。
'''
import tensorflow as tf
import resource
import numpy as np
"""
交互式InteractiveSession的話,不需要寫成session.run(Z)
可以直接寫成 .eval()。這樣寫是直接用默認(rèn)的session。不一定是你想用的那個session
"""
session = tf.InteractiveSession()
X = tf.constant(np.eye(1000))
Y = tf.constant(np.random.randn(1000,300))
#此時Z并沒有進(jìn)行計算。
Z = tf.matmul(X,Y)
Z.eval()
print("{}Kb").format(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
session.close()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
第三課
#-- coding: UTF-8 --
# 本節(jié)主要講如何更新
import tensorflow as tf
import numpy as np
x = tf.placeholder("float")
y = tf.placeholder("float")
w = tf.Variable([1.0,2.0],name="w")
y_model = tf.mul(x,w[0])+w[1]
error = tf.square(y-y_model)
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(error)
model = tf.initialize_all_variables()
errors = []
with tf.Session() as session:
session.run(model)
for i in range(1000):
x_train = tf.random_normal((1,), mean=5, stddev=2.0)
y_train = x_train * 2 + 6
x_value, y_value = session.run([x_train, y_train])
_, error_value = session.run([train_op, error], feed_dict={x: x_value, y: y_value})
errors.append(error_value)
w_value = session.run(w)
print("Predicted model: {a:.3f}x + {b:.3f}".format(a=w_value[0], b=w_value[1]))
import matplotlib.pyplot as plt
plt.plot([np.mean(errors[i-50:i]) for i in range(len(errors))])
plt.show()
plt.savefig("errors.png")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
第四課
#-- coding: UTF-8 --
import sys
import numpy as np
import tensorflow as tf
from datetime import datetime
r"""
主要知識點:
1. 如何使用GPU
-- 如果是用CPU的話,直接
# 設(shè)置各種操作序列集合
with tf.Session() as sess:
# session.run()
--如果改用GPU的話。則要在操作序列定義前面加上tf.device("/gpu:0")
with tf.device("/gpu:0"):
# 設(shè)置各種操作序列集合
with tf.Session() as sess:
# session.run()
2. 在跑的時候可以讓加些選項:
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)):
其中allow_soft_placement能讓tensorflow遇到無法用GPU跑的數(shù)據(jù)時,自動切換成CPU進(jìn)行。
log_device_placement則記錄一些日志。
運行方式:
python gpuTest.py gpu 1500
"""
device_name = sys.argv[1]
shape = (int(sys.argv[2]),int(sys.argv[2]))
if device_name == "gpu":
device_name = "/gpu:0"
else:
device_name = "/cpu:0"
# 在操作定義前面加上這個
with tf.device(device_name):
random_matrix = tf.random_uniform(shape=shape,minval=0,maxval=1)
dot_operation = tf.matmul(random_matrix,tf.transpose(random_matrix))
sum_operation = tf.reduce_sum(dot_operation)
startTime = datetime.now()
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as session:
result = session.run(sum_operation)
print(result)
print("\n"*5)
print("Shape:",shape,"Device:",device_name)
print("Time taken:",datetime.now()-startTime)
print("\n"*5)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
附加
直接安裝pip后,發(fā)現(xiàn)默認(rèn)沒有Scipy,但是直接pip install scipy會出現(xiàn)問題,SciPy和numpy這兩個科學(xué)計算包的依賴關(guān)系較多,安裝過程較為復(fù)雜。終于從網(wǎng)上看到了一個可行的方案。
sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose
另外,最好的方法是在anaconda中安裝,這個軟件默認(rèn)安裝上百個庫,基本上你要用的都有,并且還能提供一個虛擬化的環(huán)境,tensorflow的官方推薦的方法就是這種。以前試過一下,但是發(fā)現(xiàn)我用vscode時不能import tensorflow。只能在終端進(jìn)入tensorflow的虛擬環(huán)境中,才能進(jìn)行import tensorflow,瞬間就不爽了。暫時還不知道如何在vscode中能調(diào)試anaconda安裝的tensorflow。所以只能直接用pip安裝了。
|