在這向大家推薦一本書-花書-動手學深度學習pytorch版,原書用的深度學習框架是MXNet,這個框架經過Gluon重新再封裝,使用風格非常接近pytorch,但是由於pytorch越來越火,個人又比較執着,想學pytorch,好,有個大神來了,把《動手學深度學習》整本書用pytorch代碼重現了,其GitHub網址為:https://github.com/ShusenTang/Dive-into-DL-PyTorch 原書GitHub網址為:https://github.com/d2l-ai/d2l-zh 看大家愛好,其實客觀的說哪個框架都行,只要能實現代碼,學會一個框架,另外的就好上手了。菜鳥的見解哈,下面是個人感覺重要的一些
索引(x[:,1])出來和view()改變形狀后,結果數據與原數據共享內存,就是修改其中一個,另外一個會跟着修改。類似於數據結構中的鏈表,指向的地址是同一個
若是想不修改原數據,可以用clone()返回一個副本再修改:x.clone().view(5,3)
item():把一個標量tensor轉成python number
梯度
標量out:out.backward() #等價於out.backward(torch.tensor(1))
張量out:調用backward()時需要傳入一個和out同形狀的權重向量進行加權求和得到一個標量
想要修改tensor的值但又不想被autograd記錄(不會影響反向傳播),可以通過tensor.data來操作
x = torch.tensor(1.0, requires_grad=True) print(x.data) # tensor(1.) print(x.data.requires_grad) # False y = 2 * x x.data *= 100 y.backward() print(x) # tensor(100.,requires_grad=True) print(x.grad) # tensor(2.) 不是tensor(200.),因為用x.data計算不被記錄到計算圖內
線性回歸實現 參考《動手學深度學習》第三章深度學習基礎-線性回歸的從零開始實現
這真是一本不錯的書,我個人感覺
%matplotlib inline:在開頭導入包前加入這個,可以在后面使用matplotlib畫圖時不用每次都調用pyplot.show()
上面的圖中,圈1是通過display包設置圖像顯示的文件格式為svg(可以算是目前最火的圖像文件格式)
圈2中的rcParams()函數可以設置圖形的各種屬性,圈2是設置圖像尺寸大小,還有
plt.rcParams['image.interpolation'] = 'nearest' #設置插值
plt.rcParams['image.cmap'] = 'gray' # 設置顏色
plt.rcParams['figure.dpi'] = 300 # 每英寸的點數(圖片分辨率)
plt.rcParams['savefig.dpi'] = 300 # 圖片像素
plt.rcParams['font.sans-serif'] = 'SimHei' # 設置字體
plt.rcParams['font.size'] = 10.0 #設置字體大小
plt.rcParams['hist.bins'] = 10 #設置直方圖分箱個數
plt.rcParams['lines.linewidth'] = 1.5 #設置線寬
plt.rcParams['text.color'] = 'red' #設置文本顏色
# 還有其他參數可以百度看看
圈3是畫散點圖,前兩個參數是x,y,為點的橫縱坐標,第三個是點的大小。其他的參數可百度
記錄一下這段讀取數據的代碼,由於本人太菜了,好不容易查懂不想再重新查
def data_iter(batch_size, features, labels): # 這里batch_size:10 features:(1000,2)的矩陣 labels是經過線性回歸公式計算得到的預測值,labels=X*w+b num_examples = len(features) # features:(1000,2) len(features):1000 indices = list(range(num_examples)) # [0,1,2...,999] random.shuffle(indices) # 將一個列表中的元素打亂,例子見下面 for i in range(0, num_examples, batch_size): # 0-1000,step=10 [0,10,20,...,999] j = torch.LongTensor(indices[i:min(i + batch_size, num_examples)]) # 取indice值,並且返回成一個tensor。最后一次可能不足一個batch故用min函數 yield features.index_select(0, j), labels.index_select(0, j) #
yield的理解請移步,https://blog.csdn.net/mieleizhi0522/article/details/82142856 很好理解的,感謝博主了
random.shuffle() # 將一個數組打亂
li = list(range(5)) # [0,1,2,3,4] random.shuffle(li) # 作用於li列表,而不是print(random.shuffle(li)),這是輸不出來的 print(li) # [3,1,0,4,2]
torch之torch.index_select(x,1,indices) # x即要從其中(tensor x中)選擇數據的tensor;1代表列,0代表行;indices篩選時的索引序號
x.index_select(n,index) # n代表從第幾維開始,index是篩選時的索引序號。index_select(input,dim,index)沿着指定維度對input切片,取index中指定的對應的項。 可以參考博客,感謝博主 https://www.jb51.net/article/174524.htm
數據特征和標簽組合
import torch.utils.data as Data batch_size = 10 dataset = Data.TensorDataset(features,labels) #把訓練數據的特征和標簽(y值) data_iter = Data.DataLoader(dataset, batch_size,shuffle=True) #讀取批量數據,批量大小為batch_size
for X, y in data_iter: # 這樣才能打出
print(X, y)
break
搭建模型:
方法1:使用nn.Module定義
from torch import nn class LinearNet(nn.Module): def __init__(self, n_feature): super(LinearNet, self).__init__() self.linear = nn.Linear(n_feature, 1) # 定義前向傳播 def forward(self, x): y = self.linear(x) return y net = LinearNet(num_inputs) print(net) #顯示網絡結構
方法2:使用nn.Sequential# nn.Sequential搭建網絡
# 寫法1 net = nn.Sequential( nn.Linear(num_inputs, 1) # 還可加入其他層 ) # 寫法2 net = nn.Sequential() net.add_module('linear', nn.Linear(num_inputs, 1)) # net.add_module..... # 寫法3 from collections import OrderedDict # python內集合的一個模塊,使用dict時無法保持key的順序,而OrderedDict可以保持key的順序 net = nn.Sequential(OrderedDict([ ('linear', nn.Linear(num_inputs, 1)) # ...... ])) print(net) print(net[0])