東莞公司網(wǎng)站策劃怎么建立網(wǎng)站
一、python入門
1.熟悉基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)——整型數(shù)據(jù),浮點型數(shù)據(jù),列表,字典,字符串;了解列表及字典的切片,插入,刪除操作。
list1 = [1, 2, 3, 4, 5]
for each in list1:print(each)
print(list1[1:4]) #左閉右開
print(list1[0:4])
print(list1[2:-1])
print(list1[2:])
print(list1[:]) #列表的切片
list1 = [1, 2, 3, 4, 5, 6]
print(list1)
list1.remove(4) #列表的刪除操作
print(list1)
del list1[3]
print(list1)
list1.append(7) #列表的插入
print(list1)
2.了解python中類的定義與操作,下面是一個簡單的例子
class person():def __init__(self, name, age):self.name = nameself.age = agedef print_name(self):print(self.name)def print_age(self):print(self.age)
創(chuàng)造一個superman類對person進行繼承:
class superman(person):def __init__(self, name, age):super(superman, self).__init__(name, age)
#這行代碼調(diào)用了父類 person 的 __init__ 方法,并傳遞了 name 和 age 參數(shù)。self.fly_ = Trueself.name = nameself.age = agedef print_name(self):print(self.name)def print_age(self):print(self.age)def fly(self):if self.fly_ == True:print("飛起來!")
3.了解矩陣與張量的基本操作
#矩陣操作
list1 = [1, 2, 3, 4, 5]
print(list1)
array = np.array(list1) #把list1轉(zhuǎn)化為矩陣
print(array)#矩陣的操作
array2 = np.array(list1)
print(array2)
array3 = np.concatenate((array, array2), axis=1)#橫向合并列表為矩陣
print(array3)
#矩陣切片
array = np.array(list1)
print(list1[1:3])
print(array[:, 1:3])#保留1 2列#跳著切
idx = [1,3]
print(array[:, idx])#保留1 3列
#張量操作
list1 = \[[1, 2, 3, 4, 5],[6, 7, 8, 9, 10],[11, 12, 13, 14, 15]]tensor1 = torch.tensor(list1)#將list1轉(zhuǎn)化為張量
print(tensor1)x = torch.tensor(3.0)
x.requires_grad_(True)#指示PyTorch需要計算x的梯度
y = x**2
y.backward()#反向傳播計算梯度
二:簡單的線性表示代碼
根據(jù)處理數(shù)據(jù),定義模型,定義損失函數(shù),優(yōu)化參數(shù)的步驟,首先生成一批數(shù)據(jù):
import torch
import matplotlib.pyplot as pltdef create_data(w, b, data_num):x = torch.normal(0, 1, (data_num, len(w))) #生成一個形狀為 (data_num, len(w)) 的張量 x,其中 data_num 是數(shù)據(jù)點的數(shù)量,len(w) 是權(quán)重向量 w 的長度(即輸入特征的數(shù)量),張量x 的每個元素都是服從標(biāo)準(zhǔn)正態(tài)分布的隨機采樣值y = torch.matmul(x, w) + b #matmul表示矩陣相乘noise = torch.normal(0, 0.01, y.shape)# 生成一個與 y 形狀相同的噪聲張量 noise,其中每個元素都是從均值為0,標(biāo)準(zhǔn)差為0.01的正態(tài)分布中隨機采樣得到的。y += noisereturn x, ynum = 500#數(shù)據(jù)行數(shù)為500true_w = torch.tensor([8.1,2,2,4])
true_b = torch.tensor(1.1)X, Y = create_data(true_w, true_b, num)#得到用于訓(xùn)練的數(shù)據(jù)集X,Y,X為500*4的數(shù)據(jù),Y為500*1的數(shù)據(jù)plt.scatter(X[:, 1], Y, 1)#利用scatter繪制散點圖
plt.show()
通過以上操作我們就得到了用于訓(xùn)練的X,Y以及w和b的真實值。按步長為batchsize訪問數(shù)據(jù)
def data_provider(data, label, batchsize): #每次訪問這個函數(shù),就提供一批數(shù)據(jù)length = len(label)indices = list(range(length))random.shuffle(indices)for each in range(0, length, batchsize):#成批訪問數(shù)據(jù)get_indices = indices[each: each+batchsize]get_data = data[get_indices]get_label = label[get_indices]yield get_data, get_label
定義loss函數(shù)為。
def fun(x, w, b):#得到y(tǒng)的預(yù)測值pred_y = torch.matmul(x, w) + breturn pred_ydef maeLoss(pre_y, y):#定義loss函數(shù)return torch.sum(abs(pre_y-y))/len(y)
使用隨機梯度下降(SGD)方法更新參數(shù),
def sgd(paras, lr): #隨機梯度下降,更新參數(shù)with torch.no_grad(): #在更新參數(shù)時,我們不需要計算梯度。for para in paras:para -= para.grad * lrpara.grad.zero_() #更新完參數(shù)后,它將每個參數(shù)的梯度清零(.zero_() 方法),以便在下一次參數(shù)更新前不會累積之前的梯度。
確定學(xué)習(xí)率lr與初始參數(shù)w_0,b_0,注意w_0與b_0的維度。
lr = 0.03
w_0 = torch.normal(0, 0.01, true_w.shape, requires_grad=True) #這個w需要計算梯度
b_0 = torch.tensor(0.01, requires_grad=True)
定義訓(xùn)練輪次與訓(xùn)練函數(shù)
epochs = 50for epoch in range(epochs):data_loss = 0for batch_x, batch_y in data_provider(X, Y, batchsize):pred_y = fun(batch_x, w_0, b_0)#前向傳播loss = maeLoss(pred_y, batch_y)#計算損失loss.backward()#反向傳播sgd([w_0, b_0], lr)#更新參數(shù)data_loss += lossprint("epoch %03d: loss: %.6f"%(epoch, data_loss))
最后數(shù)據(jù)可視化
print("真實的函數(shù)值是", true_w, true_b)
print("訓(xùn)練得到的參數(shù)值是", w_0, b_0)idx = 0#某一列X數(shù)據(jù)
plt.plot(X[:, idx].detach().numpy(), X[:, idx].detach().numpy()*w_0[idx].detach().numpy() + b_0.detach().numpy())
plt.scatter(X[:, idx], Y, 1)
plt.show()
完整代碼如下:
import torch
import matplotlib.pyplot as plt #畫圖必備
#產(chǎn)生隨機數(shù)
import randomdef create_data(w, b, data_num): #生成數(shù)據(jù)x = torch.normal(0, 1, (data_num, len(w)))y = torch.matmul(x, w) + b #matmul表示矩陣相乘noise = torch.normal(0, 0.01, y.shape)y += noisereturn x, ynum = 500true_w = torch.tensor([8.1,2,2,4])
true_b = torch.tensor(1.1)X, Y = create_data(true_w, true_b, num)plt.scatter(X[:, 1], Y, 1)
plt.show()def data_provider(data, label, batchsize): #每次訪問這個函數(shù),就提供一批數(shù)據(jù)length = len(label)indices = list(range(length))random.shuffle(indices)for each in range(0, length, batchsize):get_indices = indices[each: each+batchsize]get_data = data[get_indices]get_label = label[get_indices]yield get_data, get_labelbatchsize = 16def fun(x, w, b):pred_y = torch.matmul(x, w) + breturn pred_ydef maeLoss(pre_y, y):return torch.sum(abs(pre_y-y))/len(y)def sgd(paras, lr): #隨機梯度下降,更新參數(shù)with torch.no_grad(): #屬于這句代碼的部分,不計算梯度for para in paras:para -= para.grad * lrpara.grad.zero_() #使用過的梯度,歸0lr = 0.03
w_0 = torch.normal(0, 0.01, true_w.shape, requires_grad=True) #這個w需要計算梯度
b_0 = torch.tensor(0.01, requires_grad=True)
print(w_0, b_0)epochs = 50for epoch in range(epochs):data_loss = 0for batch_x, batch_y in data_provider(X, Y, batchsize):pred_y = fun(batch_x, w_0, b_0)loss = maeLoss(pred_y, batch_y)loss.backward()sgd([w_0, b_0], lr)data_loss += lossprint("epoch %03d: loss: %.6f"%(epoch, data_loss))print("真實的函數(shù)值是", true_w, true_b)
print("訓(xùn)練得到的參數(shù)值是", w_0, b_0)idx = 0
plt.plot(X[:, idx].detach().numpy(), X[:, idx].detach().numpy()*w_0[idx].detach().numpy() + b_0.detach().numpy())
plt.scatter(X[:, idx], Y, 1)
plt.show()