PyTorch là một trong framework được xây cất dựa trên pynhỏ bé cung ứng nền tảng tính toán thù kỹ thuật Giao hàng nghành nghề dịch vụ Deep learning. Pytorch triệu tập vào 2 tài năng chính:
Một sự sửa chữa thay thế mang đến bộ thỏng viện numpy nhằm tận dụng tối đa sức khỏe tính toán của GPU.Một platsize Deep learning ship hàng vào nghiên cứu, đem về sự linch hoạt cùng vận tốc.Bạn đang xem: Hướng dẫn tất tần tật về pytorch là gì, học pytorch (phần 1)
Ưu điểm:
Mang lại tài năng debug dễ ợt hơn theo hướng interactively, tương đối nhiều đơn vị nghiên cứu và engineer vẫn sử dụng cả pytorch với tensorflow phần lớn Reviews cáo pytorch rộng trong sự việc debug cùng visualize.Hỗ trợ giỏi dynamic graphs.Được cải tiến và phát triển bởi vì lực lượng Facebook.Kết vừa lòng cả những API cao cấp cùng cấp thấp.Nhược điểm:
Vẫn chưa được hoàn thiện vào việc deploy, vận dụng cho các khối hệ thống Khủng,... được nhỏng framework thành lập và hoạt động trước nó như tensorflow.Ngoài document chính trường đoản cú pytorch thì vẫn còn đấy tương đối giảm bớt những nguồn tư liệu bên phía ngoài nlỗi những tutorials xuất xắc những câu hỏi trên stackoverflow.Pytorch cơ bản# import numpy libraryimport numpy as np# numpy arrayarray = <<1,2,3>,<4,5,6>>first_array = np.array(array) # 2x3 arrayprint("Array Type: ".format(type(first_array))) # typeprint("Array Shape: ".format(np.shape(first_array))) # shapeprint(first_array)output:
Array Type: Array Shape: (2, 3)<<1 2 3> <4 5 6>>Chúng ta sẽ hiểu qua về numpy array giờ đồng hồ hãy cùng xem bí quyết implement tensor array(pytorch array).
Thêm thỏng viện pytorch bằng chiếc code: import torchChúng ta tạo thành tensor cùng với hàm torch.Tensor().type: Kiểu array. Trong ví dụ này là tensor.shape: form size của array. Hàng x Cột# import pytorch libraryimport torch# pytorch arraytensor = torch.Tensor(array)print("Array Type: ".format(tensor.type)) # typeprint("Array Shape: ".format(tensor.shape)) # shapeprint(tensor)output:
Array Type: Array Shape: torch.Size(<2, 3>) 1 2 3 4 5 6
Hãy cùng so sánh numpy và tensor:
np.ones() = torch.ones()np.random.rand() = torch.rand()# numpy onesprint("Numpy ".format(np.ones((2,3))))# pytorch onesprint(torch.ones((2,3)))output:
Numpy <<1. 1. 1.> <1. 1. 1.>> 1 1 1 1 1 1
# numpy randomprint("Numpy ".format(np.random.rand(2,3)))# pytorch randomprint(torch.rand(2,3))output:
Hãy cùng coi giải pháp chuyển qua lại giữa tensor và numpy array:
torch.from_numpy(): tự numpy lịch sự tensornumpy(): trường đoản cú tensor sang numpy# random numpy arrayarray = np.random.rand(2,2)print(" ".format(type(array),array))# from numpy to lớn tensorfrom_numpy_to_tensor = torch.from_numpy(array)print(" ".format(from_numpy_to_tensor))# from tensor khổng lồ numpytensor = from_numpy_to_tensorfrom_tensor_to_numpy = tensor.numpy()print(" ".format(type(from_tensor_to_numpy),from_tensor_to_numpy))output:
1 1 1 1 1 1 1 1 1Variables
Nếu chúng ta chưa có kỹ năng về backpropagation hay gradient thì chúng ta bắt buộc phát âm bài viết về neural network của chính bản thân mình trên trên đây nhằm hoàn toàn có thể gọi được các phần tiếp theo sau.
Variable là class bao bọc (wrapper) Tensor được cho phép triển khai tính toán thù đạo hàm. Variable tàng trữ data (tensor) và grad (gradient).
Xem thêm: Dịu Dàng Một Nửa — Xkcn Là Gì ? Thắc Mắc Từ Lâu? Xkcn: Dieuthuy By Trangpham111 ♥ A Lot More At
# import variable from pytorch libraryfrom torch.autograd import Variable# define variablevar = Variable(torch.ones(3), requires_grad = True)varoutput:
Variable containing: 1 1 1
y = Variable containing: 4 16Autograd
Minch họa phương pháp tính Gradient tự động hóa trong Pytorch bằng ví dụ sau: Cho thứ thị tính toán thù nlỗi hình. Đầu vào
import torchfrom torch.autograd import Variablexy = Variable(torch.FloatTensor(<5, 3>), requires_grad=True) # size: 2z = Variable(torch.FloatTensor(<7>), requires_grad=True) # size: 1w12 = Variable(torch.FloatTensor(<0.5, 0.5>), requires_grad=True) # size: 2w3 = Variable(torch.FloatTensor(<0.5>), requires_grad=True) # size: 1w4 = Variable(torch.FloatTensor(<0.5>), requires_grad=True) # size: 1w5 = Variable(torch.FloatTensor(<0.5>), requires_grad=True) # size: 1k = xy*w12o1 = k<0>*k<1>o2 = o1*w4 + z*w3result = o2*w5print("result", result) # 2.6875result.backward()print("w12.grad", w12.grad) # 1.8750, 1.8750print("w3.grad", w3.grad) # 3.5000print("w4.grad", w4.grad) # 1.8750print("w5.grad", w5.grad) # 5.3750Giải ưa thích :
Forward:
o1 = x * w1 * y * w2 = 5 * 0.5 * 3 * 0.5 = 3.75
o2 = o1 * w4 + z * w3 = 3.75 * 0.5 + 7 * 0.5 = 5.375
result = o2 * w5 = 5.375 * 0.5 = 2.6875
Backward:
Cần chú ý công thức đạo hàm của hàm hợp:
f"(u(x)) = f"(u) * u"(x)
result = o2 * w5
Đạo hàm của result theo w5 = (o2 * w5)" = o2 = 5.375
Đạo hàm của result theo o2 = f"(o2) = w5 = 0.5
o2 = o1 * w4 + z * w3
Đạo hàm của result theo w3 = f"(o2) * o2"(w3) = 0.5 * z = 3.5
Đạo hàm của result theo w4 = f"(o2) * o2"(w4) = 0.5 * o1 = 1.875
Đạo hàm của result theo o1 = g"(o1) = f"(o2) * o2"(o1) = 0.5 * w4 = 0.25
o1 = x * w1 * y * w2
Đạo hàm của result theo w1 = g"(o1) * o1"(w1) = 0.25 * x * y * w2 = 1.875
Đạo hàm của result theo w2 = g"(o1) * o1"(w2) = 0.25 * x * w1 * y = 1.875
Nếu chúng ta chưa có kỹ năng và kiến thức về Linear Regression thì có thể tìm hiểu thêm trên đây.
Hàm y = Ax + B.Ví dụ: mang sử họ có một đơn vị xe hơi. Nếu giá chỉ xe cộ xuống rẻ, bọn họ đang phân phối được không ít xe cộ hơn. Nếu giá xe tăng cao, ta bán được không nhiều xe pháo hơn. Đây là thực tiễn nhưng mà chúng ta biết và họ có dữ liệu về vấn đề đó.Câu hỏi đưa ra là làm sao nhằm ước lượng được số xe cộ ta đang bán được Khi mà giá xe pháo là 100.# As a oto company we collect this data from previous selling# lets define oto pricescar_prices_array = <3,4,5,6,7,8,9>car_price_np = np.array(car_prices_array,dtype=np.float32)car_price_np = car_price_np.reshape(-1,1)car_price_tensor = Variable(torch.from_numpy(car_price_np))# lets define number of car sellnumber_of_car_sell_array = < 7.5, 7, 6.5, 6.0, 5.5, 5.0, 4.5>number_of_car_sell_np = np.array(number_of_car_sell_array,dtype=np.float32)number_of_car_sell_np = number_of_car_sell_np.reshape(-1,1)number_of_car_sell_tensor = Variable(torch.from_numpy(number_of_car_sell_np))# lets visualize our dataimport matplotlib.pyplot as pltplt.scatter(car_prices_array,number_of_car_sell_array)plt.xlabel("Car Price $")plt.ylabel("Number of Car Sell")plt.title("Car Price$ VS Number of Car Sell")plt.show()
Hình bên trên ta sẽ plot tài liệu nhưng mà ta tích lũy được và câu hỏi đặt ra là kiếm tìm con số xe pháo sẽ bán được lúc giá chỉ xe hơi là 100. Để vấn đáp câu hỏi này ta đang bắt buộc sử dụng Linear Regression. Về cơ phiên bản họ đã nạm tạo thành một con đường thẳng fit với tài liệu đã được plot ngơi nghỉ trên với nỗ lực tinh chỉnh mặt đường trực tiếp kia làm thế nào để cho bớt được độ lệch vs data.
Các bước tiến hành Linear Regression
Tạo lớp LinearRegressionTạo Mã Sản Phẩm vào class LinearRegressionMSE: Mean squared errorOptimization (SGD:stochastic gradient descent)BackpropagationĐưa ra dự đoán# Linear Regression with Pytorch# librariesimport torch from torch.autograd import Variable import torch.nn as nn import warningswarnings.filterwarnings("ignore")# create classclass LinearRegression(nn.Module): def __init__(self,input_kích thước,output_size): # super function. It inherits from nn.Module & we can access everythink in nn.Module super(LinearRegression,self).__init__() # Linear function. self.linear = nn.Linear(input_dyên,output_dim) def forward(self,x): return self.linear(x) # define modelinput_dyên = 1output_dyên ổn = 1Model = LinearRegression(input_dyên,output_dim) # đầu vào & output size are 1# MSEmse = nn.MSELoss()# Optimization (find parameters that minimize error)learning_rate = 0.02 # how fast we reach best parametersoptimizer = torch.optyên.SGD(model.parameters(),lr = learning_rate)# train modelloss_menu = <>iteration_number = 1001for iteration in range(iteration_number): # optimization optimizer.zero_grad() # Forward lớn get output results = model(car_price_tensor) # Calculate Loss loss = mse(results, number_of_car_sell_tensor) # backward propagation loss.backward() # Updating parameters optimizer.step() # store loss loss_danh sách.append(loss.data) # print loss if(iteration % 50 == 0): print("epoch , loss ".format(iteration, loss.data))plt.plot(range(iteration_number),loss_list)plt.xlabel("Number of Iterations")plt.ylabel("Loss")plt.show()output:
epoch 0, loss 10.2133
# predict our car price predicted = model(car_price_tensor).data.numpy()plt.scatter(car_prices_array,number_of_car_sell_array,label = "original data",color ="red")plt.scatter(car_prices_array,predicted,label = "predicted data",color ="blue")# predict if oto price is 10$, what will be the number of oto sell#predicted_10 = model(torch.from_numpy(np.array(<10>))).data.numpy()#plt.scatter(10,predicted_10.data,label = "oto price 10$",color ="green")plt.legend()plt.xlabel("Car Price $")plt.ylabel("Number of Car Sell")plt.title("Original vs Predicted values")plt.show()
Mình mong muốn cùng với phần 1 này chúng ta đang có tác dụng quen thuộc được với pytorch với hoàn toàn có thể từ bỏ mình code thạo được một trong những chức năng cơ bản. Tại phần 2 chúng ta đang bước vào mày mò bí quyết implement pytorch mang lại một trong những quy mô deep learning.