南京斯点企业网站建设,百度手机助手官网,网站规划设计,做内贸现在一般都通过哪些网站一、python入门
1.熟悉基础数据结构——整型数据#xff0c;浮点型数据#xff0c;列表#xff0c;字典#xff0c;字符串#xff1b;了解列表及字典的切片#xff0c;插入#xff0c;删除操作。
list1 [1, 2, 3, 4, 5]
for each in list1:print(each)
print(list1[1…一、python入门
1.熟悉基础数据结构——整型数据浮点型数据列表字典字符串了解列表及字典的切片插入删除操作。
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)创造一个superman类对person进行继承
class superman(person):def __init__(self, name, age):super(superman, self).__init__(name, age)
#这行代码调用了父类 person 的 __init__ 方法并传递了 name 和 age 参数。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转化为矩阵
print(array)#矩阵的操作
array2 np.array(list1)
print(array2)
array3 np.concatenate((array, array2), axis1)#横向合并列表为矩阵
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转化为张量
print(tensor1)x torch.tensor(3.0)
x.requires_grad_(True)#指示PyTorch需要计算x的梯度
y x**2
y.backward()#反向传播计算梯度
二简单的线性表示代码
根据处理数据定义模型定义损失函数优化参数的步骤首先生成一批数据
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 是数据点的数量len(w) 是权重向量 w 的长度即输入特征的数量张量x 的每个元素都是服从标准正态分布的随机采样值y torch.matmul(x, w) b #matmul表示矩阵相乘noise torch.normal(0, 0.01, y.shape)# 生成一个与 y 形状相同的噪声张量 noise其中每个元素都是从均值为0标准差为0.01的正态分布中随机采样得到的。y noisereturn x, ynum 500#数据行数为500true_w torch.tensor([8.1,2,2,4])
true_b torch.tensor(1.1)X, Y create_data(true_w, true_b, num)#得到用于训练的数据集XYX为500*4的数据Y为500*1的数据plt.scatter(X[:, 1], Y, 1)#利用scatter绘制散点图
plt.show()
通过以上操作我们就得到了用于训练的XY以及w和b的真实值。按步长为batchsize访问数据
def data_provider(data, label, batchsize): #每次访问这个函数就提供一批数据length len(label)indices list(range(length))random.shuffle(indices)for each in range(0, length, batchsize):#成批访问数据get_indices indices[each: eachbatchsize]get_data data[get_indices]get_label label[get_indices]yield get_data, get_label
定义loss函数为。
def fun(x, w, b):#得到y的预测值pred_y torch.matmul(x, w) breturn pred_ydef maeLoss(pre_y, y):#定义loss函数return torch.sum(abs(pre_y-y))/len(y)使用随机梯度下降SGD方法更新参数
def sgd(paras, lr): #随机梯度下降更新参数with torch.no_grad(): #在更新参数时我们不需要计算梯度。for para in paras:para - para.grad * lrpara.grad.zero_() #更新完参数后它将每个参数的梯度清零.zero_() 方法以便在下一次参数更新前不会累积之前的梯度。
确定学习率lr与初始参数w_0b_0注意w_0与b_0的维度。
lr 0.03
w_0 torch.normal(0, 0.01, true_w.shape, requires_gradTrue) #这个w需要计算梯度
b_0 torch.tensor(0.01, requires_gradTrue)
定义训练轮次与训练函数
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(真实的函数值是, true_w, true_b)
print(训练得到的参数值是, w_0, b_0)idx 0#某一列X数据
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 #画图必备
#产生随机数
import randomdef create_data(w, b, data_num): #生成数据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): #每次访问这个函数就提供一批数据length len(label)indices list(range(length))random.shuffle(indices)for each in range(0, length, batchsize):get_indices indices[each: eachbatchsize]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): #随机梯度下降更新参数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_gradTrue) #这个w需要计算梯度
b_0 torch.tensor(0.01, requires_gradTrue)
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(真实的函数值是, true_w, true_b)
print(训练得到的参数值是, 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()