有需要這本書的pdf資源的可以聯(lián)系我~
這本書不是偏向于非常詳細(xì)的教你很多函數(shù)怎么用,更多的是交個(gè)基本使用,主要是后面的深度學(xué)習(xí)相關(guān)的內(nèi)容。
1.Numpy提供兩種基本的對象:ndarray(n維數(shù)組對象)(用于儲(chǔ)存多維數(shù)據(jù))和ufunc(通用函數(shù)對象,用于處理不同的數(shù)據(jù))。
2.numpy的主要優(yōu)點(diǎn):ndarray提供了很多數(shù)組化的運(yùn)算,并且可以快讀對數(shù)組進(jìn)行操作,不用寫循環(huán)來操作。
3.numpy是外部的庫,使用的話需要導(dǎo)入先,沒有庫可以安裝。
4.使用時(shí)候要導(dǎo)入numpy
5.創(chuàng)建ndarry的方法
注意:
range是個(gè)范圍一般是用在for里的
arange是一種快捷生成方式,幾到幾隔幾個(gè)這種,或者直接生成然后reshape
array一般用于生成有具體內(nèi)容的ndarry
import numpy as np
#1.使用轉(zhuǎn)換函數(shù)將現(xiàn)有的list或者元組轉(zhuǎn)換為ndarry
list1=[[3.14,2.17,0,1,2],[3,44,2.22,55,9]]
nd1=np.array(list1)
print(nd1)
#2.use the random to generate the ndarry
nd2=np.random.random([3,3])
print(nd2)
#指定了seed之后就會(huì)生成固定的內(nèi)容
nd3=np.random.random([3,3])
print(nd3)
#3.使用便捷生成函數(shù)zeros、ones等,可可以將生成的結(jié)果進(jìn)行保存
nd4=np.zeros((3,4),int)#默認(rèn)是float類型
np.savetxt(X=nd4,fname='./test1.txt')
print(nd4)
#4.使用arange和linspace函數(shù)生成數(shù)組
nd4=np.arange(4,50,12)#4-50 per 12 ,no including 50
print(nd4)
nd5=np.arange(9,-1,-2)#倒著生成需要在步長前添加-
print(nd5)
nd6=np.linspace(0,4,8)#在0-4之間均勻的生成8個(gè),包含起點(diǎn)和終點(diǎn),等差數(shù)列
print(nd6)
nd7=np.logspace(0,4,8,base=2)#等比數(shù)列
print(nd7)
6.獲取元素
#獲取元素
nd8=np.random.random(10)
print(nd8)
print(nd8[3])#從0開始算,其實(shí)是第四個(gè)
print(nd8[3:6])#索引為3的開始一直到索引為5,不包括6
print(nd8[1:6:2])#索引1到索引5,每隔1個(gè)取一個(gè)
print(nd8[1:6:1])#每隔0個(gè),也就是挨個(gè)取
print(nd8[::-2])#倒序每隔兩個(gè)
nd9=np.arange(25).reshape([5,5])
print('nd9:',nd9)
print('second and third row:',nd9[1:3,:])#指定行,先行后列
print('second and third row:',nd9[[1,2]])#指定行
print('second and third cloum:',nd9[:,1:3])#指定列
print(nd9[1:5,1:3])#先行后列
print('range[2,8]:',nd9[(nd9>2)&(nd9<8)])#篩選
7.運(yùn)算
#算數(shù)運(yùn)算
#主要用到的就是乘法:普通乘法(對應(yīng)元素相乘)和點(diǎn)乘(內(nèi)積)
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])
C = np.array([3,5,6])
print(A)
print(B)
print(A*B)#數(shù)乘
print(np.multiply(A,B))#數(shù)乘
print(3*A)#數(shù)乘
print(B/3.0)#數(shù)乘
D = np.random.rand(4,2)
def softmoid(x):#定義一個(gè)函數(shù)
return 1/(1+np.exp(-x))
print(D)
print(softmoid(D))
print(softmoid(D).shape)#輸出數(shù)據(jù)的shape,就是形狀大小
print(np.shape(D))#函數(shù)的形式輸出和上面是一樣的意思
print(softmoid(D).size)#size是個(gè)數(shù)
X1 = np.array([[1,2],[3,4]])
X2 = np.array([[5,6,7],[8,9,10]])
print(np.dot(X1,X2))
8.數(shù)組變形
#數(shù)據(jù)變形
#reshape()改變維度,不改變數(shù)組本身
X1 = np.arange(10)
print(X1)
print(X1.reshape(2,5))
print(X1.reshape(-1,5))
print(X1)
#resize改變維度,改變數(shù)組本身
print(X1.resize(2,5))
print(X1)
#轉(zhuǎn)置
print(X1.T)
#展平如果我們將 order 參數(shù)設(shè)置為“C”,則意味著數(shù)組以行優(yōu)先順序展平。
#如果設(shè)置了“F”,則數(shù)組將按列優(yōu)先順序展平。
#僅當(dāng)“A”在內(nèi)存中是 Fortran 連續(xù)的并且我們將 order 參數(shù)設(shè)置為“A”時(shí),數(shù)組才以列優(yōu)先順序展平。
#最后一個(gè)順序是“K”,它以與元素在內(nèi)存中出現(xiàn)的順序相同的順序展平數(shù)組。默認(rèn)情況下,此參數(shù)設(shè)置為“C”。
print(X1.ravel())#按照行展平,default
print(X1.ravel('F'))#按照列展平
print(X1.ravel('C'))#按照行展平
#flatten 把矩陣轉(zhuǎn)換為向量,這種需求經(jīng)常出現(xiàn)在卷積網(wǎng)絡(luò)與全連接層之間。
a =np.floor(10*np.random.random((3,4)))#floor取整
print(a)
print(a.flatten())
#squeeze降維 這是一個(gè)主要用來降維的函數(shù),把矩陣中含1的維度去掉,不改變原變量。在PyTorch中還有一種與之相反的操作——torch.unsqueeze
arr1 = np.arange(3).reshape(3,1)
print(arr1)
print(arr1.shape)
print(arr1.squeeze())
print(arr1.squeeze().shape)
print(arr1)
print(arr1.shape)
arr2 =np.arange(6).reshape(3,1,2,1)#
print(arr2)
print(arr2.shape)
print(arr2.squeeze().shape)
print(arr2.squeeze())#去掉了兩個(gè)維度,就是為1的維度
#transpose 對高維矩陣進(jìn)行軸對換,這個(gè)在深度學(xué)習(xí)中經(jīng)常使用,比如把圖片中表示顏色順序的RGB改為GBR
arr3 = np.arange(24).reshape(2,3,4)
print(arr3)
print(arr3.shape)
print(arr3.transpose(1,2,0))#索引代表了如何進(jìn)行軸對換0和2換,1在和2換
print(arr3.transpose(1,2,0).shape)
9.合并
#數(shù)組合并,按照行合并就是按照行往下走,合并到下面;按照列合并就是往右走,放到右邊
#1.append
a=np.array([1,2,3])
b=np.array([4,5,6])
print(np.append(a,b))#合并一維數(shù)組
c=np.arange(4).reshape(2,2)
d=np.arange(4).reshape(2,2)
print(np.append(c,d,axis=0))#=0按照行合并
print(np.append(c,d,axis=1))#=1按照列合并
#2.concatenate按照指定軸連接數(shù)組或矩陣,要連接的那個(gè)方向維度大小要一致
e = np.array([[1,2],[3,4]])#2*2
f = np.array([[5,6]])#2*1
print(np.concatenate((e,f),axis=0))
#print(np.concatenate((e,f),axis=1))#列的尺寸不一樣 會(huì)報(bào)錯(cuò),可以轉(zhuǎn)置之后再拼接
print(np.concatenate((e,f.T),axis=1))
#3.stack 沿著制定軸堆疊數(shù)組和矩陣,只是單純的堆疊
print(np.stack((e,e),axis=0))
10.批處理
#批處理:1.獲得數(shù)據(jù)集2.打亂3.定義批大小4.處理
data_train = np.random.randn(10000,2,3)#create 10000 2*3 ndarry
print(data_train.shape)
np.random.shuffle(data_train)#打亂
batch_size = 100
for i in range(0,len(data_train),batch_size):
x_batch_sum = np.sum(data_train[i:i+batch_size])
print('第{}批,該批次之和:{}'.format(i,x_batch_sum))
11.通用函數(shù)
#通用函數(shù) ufunc 對數(shù)組的每個(gè)元素進(jìn)行處理的一類函數(shù) 。
#math模塊的輸入一般是標(biāo)量,但Numpy中的函數(shù)可以是向量或矩陣,而利用向量或矩陣可以避免使用循環(huán)語句,這點(diǎn)在機(jī)器學(xué)習(xí)、深度學(xué)習(xí)中非常重要
x=[i*0.001 for i in np.arange(1000000)]
start = time.perf_counter()#計(jì)時(shí)器開始,到最后在記一次然后減去最初的
for i,t in enumerate(x):
x[i]=math.sin(t)#math中必須對每個(gè)元素逐個(gè)sin
print ("math.sin:", time.perf_counter() - start )
y = [i * 0.001 for i in np.arange(1000000)]
y = np.array(y)
tic = time.process_time()#計(jì)時(shí)器
np.sin(y)#可以直接對ndarry來使用
toc = time.process_time()
print ("numpy.sin:", toc - tic )
11.廣播機(jī)制:就是補(bǔ)齊數(shù)組,讓shape相同
#廣播機(jī)制:也就是數(shù)組的shape不一致時(shí),會(huì)自動(dòng)補(bǔ)齊
#補(bǔ)齊規(guī)則:
#1.讓所有輸入數(shù)組都向其中shape最長的數(shù)組看齊,不足的部分則通過在前面加1補(bǔ)齊a:2×3×2 b:3×2 則b向a看齊,在b的前面加1,變?yōu)椋?×3×2
#2.輸出數(shù)組的shape是輸入數(shù)組shape的各個(gè)軸上的最大值
#3.如果輸入數(shù)組的某個(gè)軸和輸出數(shù)組的對應(yīng)軸的長度相同或者某個(gè)軸的長度為1時(shí),這個(gè)數(shù)組能被用來計(jì)算,否則出錯(cuò)
#4.當(dāng)輸入數(shù)組的某個(gè)軸的長度為1時(shí),沿著此軸運(yùn)算時(shí)都用(或復(fù)制)此軸上的第一組值
#官網(wǎng)http://www.Numpy.org/
Pytorch的學(xué)習(xí)
1.numpy和tensor的最大的區(qū)別就是Numpy會(huì)把ndarray放在CPU中進(jìn)行加速運(yùn)算,而由Torch產(chǎn)生的Tensor會(huì)放在GPU中進(jìn)行加速運(yùn)算,如果有GPU的話。
2.使用tensor操作函數(shù)主要有兩種:一種是torch.add(x,y)一種是x.add(y)。一種是從torch函數(shù)角度出發(fā),一種是從tensor出發(fā)。
?3.每個(gè)函數(shù)都可以實(shí)現(xiàn)修改原變量,運(yùn)行符帶下劃線后綴
4.創(chuàng)建tensor
?最好用Tensor,大寫T的指令tensor和Tensor有一些區(qū)別,用Tensor更方便,tensor(2,3)會(huì)報(bào)錯(cuò)
5.修改tensor的形狀
torch.view=torch.reshape
如果你只想重塑張量,請使用torch.reshape。如果你還關(guān)注內(nèi)存使用情況并希望確保兩個(gè)張量共享相同的數(shù)據(jù),請使用torch.view。
注意:沒有resize()這個(gè)函數(shù)
?6.索引操作
?7.逐元素操作
?8.歸并操作
?9.比較操作
?10矩陣操作
?11.numpy和pytorch區(qū)別
12.求梯度
12.1標(biāo)量求梯度
調(diào)用backward()并且不需要傳入?yún)?shù),loss通常是標(biāo)量值
12.2非標(biāo)量求梯度
要分別求,backward里要帶著參數(shù)(1,0)就是第一個(gè),除此之外因?yàn)槭翘荻鹊睦奂樱笸暌徊糠志鸵?
13實(shí)現(xiàn)簡單的機(jī)器學(xué)習(xí)
import torch as t
%matplotlib inline
from matplotlib import pyplot as plt
dtype=t.float
t.manual_seed(100)
lr=0.001
x=t.unsqueeze(t.linspace(-1,1,100),dim=1)
y=3*x.pow(2)+2+0.2*t.rand(x.size())
#plt.scatter(x.numpy(),y.numpy())
#plt.show()
w=t.randn(1,1,dtype=dtype,requires_grad=True)
b=t.zeros(1,1,dtype=dtype,requires_grad=True)
for ii in range(800):
y_pred=x.pow(2).mm(w)+b
loss=0.5*(y_pred-y)**2
loss=loss.sum()
loss.backward()
#手動(dòng)更新參數(shù)
with t.no_grad():
w-=lr*w.grad
b-=lr*w.grad
w.grad.zero_()
b.grad.zero_()
plt.plot(x.numpy(),y_pred.detach().numpy(),'r-',label='predict')#畫線(繪制經(jīng)過點(diǎn)的曲線)
plt.scatter(x.numpy(),y.numpy(),color='blue',marker='o',label='true')#繪制散點(diǎn)圖(繪制那些點(diǎn))
plt.xlim(-1,1)#指定坐標(biāo)軸的值的范圍
plt.ylim(2,6)
plt.legend()#結(jié)合label創(chuàng)建圖例
plt.show()
print(w,b)
14.神經(jīng)網(wǎng)絡(luò)的核心組件
通常使用pytorch的nn工具箱,會(huì)有現(xiàn)成的包或類
層:將輸入張量轉(zhuǎn)換為輸出張量;
模型:層構(gòu)成的網(wǎng)絡(luò);
損失函數(shù):參數(shù)學(xué)習(xí)的目標(biāo)函數(shù),也是優(yōu)化的目標(biāo),通常讓損失函數(shù)最??;
優(yōu)化器:如何使損失函數(shù)最??;
?15.實(shí)例
15.1構(gòu)建網(wǎng)絡(luò)層:構(gòu)建網(wǎng)絡(luò)層通常有兩種,一種是nn.module,另一種是nn.functional,
具有學(xué)習(xí)參數(shù)的(例如,conv2d,linear,batch_norm)采用nn.Xxx方式。沒有學(xué)習(xí)參數(shù)的(例如,maxpool、loss func、activation func)等根據(jù)個(gè)人選擇使用nn.functional.xxx或者nn.Xxx方式
?
import numpy as np
import torch
from torchvision.datasets import mnist#導(dǎo)入數(shù)據(jù)集
import torchvision.transforms as transforms#數(shù)據(jù)預(yù)處理的包,一般來說是要用的
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
from torch import nn
import matplotlib.pyplot as plt
%matplotlib inline
#定義超參數(shù)
train_batch_size = 64
test_batch_size = 128
learning_rate = 0.01
num_epoches = 20
lr = 0.01
momentum = 0.5
#下載數(shù)據(jù)并進(jìn)行預(yù)處理
#預(yù)處理函數(shù)要統(tǒng)一放到compose中,目前有將數(shù)據(jù)轉(zhuǎn)換為tensor的處理以及數(shù)據(jù)歸一化(三個(gè)通道則是【m1,m2,m3】,【n1,n2,n3】)
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize([0.5],[0.5])])
#下載數(shù)據(jù),并且進(jìn)行預(yù)處理
train_dataset = mnist.MNIST('./data',train=True,transform=transform,download=True)
test_dataset = mnist.MNIST('./data',train=False,transform=transform)
#dataloader 要將數(shù)據(jù)放到dataloader迭代器中,如果是自己的數(shù)據(jù)也要按照格式放到dataloader中
train_loader = DataLoader(train_dataset,batch_size=train_batch_size,shuffle=True)
test_loader = DataLoader(test_dataset,batch_size=test_batch_size,shuffle=True)
#顯示數(shù)據(jù)
examples = enumerate(test_loader)#標(biāo)簽和數(shù)據(jù)進(jìn)行對應(yīng)
batch_idx,(example_data,example_target) = next(examples)#取出可以迭代的對象
# fig = plt.figure()
# for i in range(6):
# plt.subplot(2,3,i+1)
# plt.tight_layout()
# plt.imshow(example_data[i][0],cmap='gray',interpolation='none')
# plt.title("GroundTruth:{}".format(example_target[i]))
# plt.xticks([])
# plt.yticks([])
#構(gòu)建網(wǎng)絡(luò),使用nn.sequential
class Net(nn.Module):
def __init__(self, in_dim,n_hidden1,n_hidden2,out_dim):#網(wǎng)絡(luò)的參數(shù)
super(Net, self).__init__()
self.layer1 = nn.Sequential(nn.Linear(in_dim,n_hidden1),nn.BatchNorm1d(n_hidden1))
#self.layer1 = nn.Sequential(nn.Linear(in_dim,n_hidden1))
self.layer2 = nn.Sequential(nn.Linear(n_hidden1,n_hidden2),nn.BatchNorm1d(n_hidden2))
#self.layer2 = nn.Sequential(nn.Linear(n_hidden1,n_hidden2))
self.layer3 =nn.Sequential(nn.Linear(n_hidden2,out_dim))
#定義前向傳播過程
def forward(self,x):
x = F.relu(self.layer1(x))
x = F.relu(self.layer2(x))
x = self.layer3(x)
return x
#實(shí)例化一個(gè)網(wǎng)絡(luò),使用gpu,沒有的話就使用cpu
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model = Net(28*28,300,100,10)
model.to(device)
#定義損失函數(shù)和優(yōu)化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(),lr=lr,momentum=momentum)
losses=[]#損失值要依次存進(jìn)來
acces=[]
eval_losses=[]
eval_acces=[]
for epoch in range(num_epoches):
train_loss = 0
train_acc = 0
model.train()
if epoch%5==0:
optimizer.param_groups[0]['lr']*=0.1
for img,label in train_loader:
img = img.to(device)#都放到gpu上計(jì)算
label = label.to(device)
img = img.view(img.size(0),-1)#展平
#print(type(img))
out=model(img)
#print(type(out))
loss=criterion(out,label)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss+=loss.item()#取出loss值
_,pred = out.max(1)
num_correct = (pred==label).sum().item()
acc=num_correct/img.shape[0]
train_acc+=acc
losses.append(train_loss/len(train_loader))
acces.append(train_acc/len(train_loader))
eval_loss=0
eval_acc=0
model.eval()
for img,label in test_loader:
img=img.to(device)
label = label.to(device)
img = img.view(img.size(0),-1)
out=model(img)
loss=criterion(out,label)
eval_loss+=loss.item()
_,pred=out.max(1)
num_correct = (pred==label).sum().item()
acc=num_correct/img.shape[0]
eval_acc+=acc
eval_losses.append(eval_loss/len(test_loader))
eval_acces.append(eval_acc/len(test_loader))
print('epoch:{},train_loss:{:.4f},trian_acc:{:.4f},test_loss:{:.4f},test_acc:{:.4f}'.format(epoch,train_loss/len(train_loader),train_acc/len(train_loader),eval_loss/len(test_loader),eval_acc/len(test_loader)))
plt.title('trainloss')
plt.plot(np.arange(len(losses)),losses)
plt.legend(['train loss'],loc='upper right')
小結(jié):
1.定義網(wǎng)絡(luò):有多種方式
2.前向傳播:forward,把輸入層和網(wǎng)絡(luò)層和輸出層鏈接起來。
3.反向傳播:使用nn工具之后,直接loss.backward()就可以,然后選一個(gè)優(yōu)化器optimizer
4.訓(xùn)練模型:model.train(),測試的話就是model.eval(),在這兩個(gè)函數(shù)之后要調(diào)用loss.backward()和optimizer.step()執(zhí)行
(注:可以使用不同的優(yōu)化器)
()
?文章來源地址http://www.zghlxwxcb.cn/news/detail-487968.html
?
?
?
?文章來源:http://www.zghlxwxcb.cn/news/detail-487968.html
?
到了這里,關(guān)于《Python深度學(xué)習(xí)基于Pytorch》學(xué)習(xí)筆記的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!