当前位置: 首页 > news >正文

佛山新网站建设如何百度联盟广告收益

佛山新网站建设如何,百度联盟广告收益,上海网站设计印刷拆除,做二手货车都做什么网站文章目录1.简单回归实战:2.手写数据识别1.简单回归实战: 用 线性回归拟合二维平面中的100个点 公式:ywxbywxbywxb 损失函数:∑(yreally−y)2\sum(y_{really}-y)^2∑(yreally​−y)2 迭代方法:梯度下降法,…

文章目录

      • 1.简单回归实战:
      • 2.手写数据识别

1.简单回归实战:

用 线性回归拟合二维平面中的100个点
在这里插入图片描述
公式:y=wx+by=wx+by=wx+b
损失函数:∑(yreally−y)2\sum(y_{really}-y)^2(yreallyy)2
迭代方法:梯度下降法,其中www,bbb更新公式如下:
wN+1=wN−η∗∂loss∂wbN+1=bN−η∗∂loss∂bw_{N+1}=w_N-\eta*\frac{\partial loss}{\partial w}\\ b_{N+1}=b_{N}-\eta*\frac{\partial loss}{\partial b}wN+1=wNηwlossbN+1=bNηbloss
其中η\etaη表示学习率,∂\partial表示微分
∂loss∂w=2(wx+b−y)x/n∂loss∂b=2(wx+b−y)/n\frac{\partial loss}{\partial w}=2(wx+b-y)x/n\\ \frac{\partial loss}{\partial b}=2(wx+b-y)/n wloss=2(wx+by)x/nbloss=2(wx+by)/n
项目文件
计算损失函数:

def compute_loss(b,w,points):total = 0for i in range(0,len(points)):x = points[i,0]y = points[i,1]total += (y-(w*x+b)) ** 2return total / float(len(points))

梯度下降迭代更新:

def gradient(b,w,points,leanrningRate):b_gradient = 0w_gradient = 0N = float(len(points))for i in range(0,len(points)):x = points[i,0]y = points[i,1]b_gradient += (2/N) * (((w * x)+b)-y)w_gradient += (2/N) * (((w * x)+b)-y) * xnew_b = b - (leanrningRate * b_gradient)new_w = w - (leanrningRate * w_gradient)return [new_b , new_w]def graient_descent_runner(points, b, w, learning_rate, num_iterations):new_b = bnew_w = wfor i in range(num_iterations):new_b, new_w = gradient(new_b, new_w, np.array(points), learning_rate)return [new_b, new_w]

主函数运行以及绘图结果:

def run():points = np.genfromtxt("data.csv",delimiter=",")learning_rate = 0.0001initial_b = 0initial_w = 0num_iteractions = 1000print("Starting gradient descent at b = {0}, w = {1}, error = {2}".format(initial_b,initial_w,compute_loss(initial_b,initial_w,points)))print("Runing...")[b, w] = graient_descent_runner(points,initial_b,initial_w,learning_rate,num_iteractions)print("After {0} iterations b = {1}, w = {2}, error = {3}".format(num_iteractions,b,w,compute_loss(b,w,points)))x = np.linspace(20, 80, 5)y = w * x + bpyplot.plot(x, y)pyplot.scatter(points[:, 0], points[:, 1])pyplot.show()if __name__ == '__main__':run()

在这里插入图片描述
在这里插入图片描述

2.手写数据识别

工具函数库:

import torch
from matplotlib import pyplot as pltdef plot_curve(data):fig = plt.figure()plt.plot(range(len(data)), data, color='blue')plt.legend(['value'], loc='upper right')plt.xlabel('step')plt.ylabel('value')plt.show()def plot_image(img, label, name):fig = plt.figure()for i in range(6):plt.subplot(2, 3, i + 1)plt.tight_layout()plt.imshow(img[i][0]*0.3081+0.1307, cmap='gray', interpolation='none')plt.title("{}: {}".format(name, label[i].item()))plt.xticks([])plt.yticks([])plt.show()def one_hot(label, depth=10):out = torch.zeros(label.size(0), depth)idx = torch.LongTensor(label).view(-1, 1)out.scatter_(dim=1, index=idx, value=1)return out

第一步:导入库和图像数据

import torch
from torch import nn #构建神经网络
from torch.nn import functional as F 
from torch import optim #最优化工具
import torchvision #视觉工具
from utils import plot_image, plot_curve, one_hotbatch_size = 512
train_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('mnist_data', train=True, download=True,transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor(),torchvision.transforms.Normalize((0.1307,), (0.3081,))])),batch_size=batch_size, shuffle=True)test_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('mnist_data/', train=False, download=True,transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor(),torchvision.transforms.Normalize((0.1307,), (0.3081,))])),batch_size=batch_size, shuffle=False)x, y = next(iter(train_loader))
print(x.shape, y.shape, x.min(), y.min())
plot_image(x, y, 'image sample')

在这里插入图片描述
第二步:新建一个三层的非线性的网层

class Net(nn.Module):def __init__(self):super(Net, self).__init__()#第一层(28*28是图片,256根据经验随机决定)self.fc1 = nn.Linear(28 * 28, 256)self.fc2 = nn.Linear(256, 64)#第三层(十分类输出一定是10)self.fc3 = nn.Linear(64, 10)def forward(self, x):# x: [b, 1, 28, 28]# h1 = relu(xw1+b1) h2 = relu(h1w2+b2) h3 = h2w3+b3x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return x

第三步:train训练

net = Net()
# [w1, b1, w2, b2, w3, b3]
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
train_loss = []for epoch in range(3):for batch_idx, (x, y) in enumerate(train_loader):# x: [b, 1, 28, 28], y: [512]# [b, 1, 28, 28] => [b, 784],将整个图片看做特征向量x = x.view(x.size(0), 28*28)# => [b, 10]out = net(x)# [b, 10]y_onehot = one_hot(y)# loss = mse(out, y_onehot)loss = F.mse_loss(out, y_onehot)optimizer.zero_grad()loss.backward()#梯度下降# w' = w - lr*gradoptimizer.step()train_loss.append(loss.item())if batch_idx % 10==0:print(epoch, batch_idx, loss.item())plot_curve(train_loss)

在这里插入图片描述
第四步:准确度测试

total_correct = 0
for x,y in test_loader:x  = x.view(x.size(0), 28*28)out = net(x)# out: [b, 10] => pred: [b]pred = out.argmax(dim=1)correct = pred.eq(y).sum().float().item()total_correct += correcttotal_num = len(test_loader.dataset)
acc = total_correct / total_num
print('test acc:', acc)x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28*28))
pred = out.argmax(dim=1)
plot_image(x, pred, 'test')

在这里插入图片描述
在这里插入图片描述
无注释代码:

import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
from utils import plot_image, plot_curve, one_hotbatch_size = 512
train_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('mnist_data', train=True, download=True,transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor(),torchvision.transforms.Normalize((0.1307,), (0.3081,))])),batch_size=batch_size, shuffle=True)test_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('mnist_data/', train=False, download=True,transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor(),torchvision.transforms.Normalize((0.1307,), (0.3081,))])),batch_size=batch_size, shuffle=False)x, y = next(iter(train_loader))
print(x.shape, y.shape, x.min(), y.min())
plot_image(x, y, 'image sample')class Net(nn.Module):def __init__(self):super(Net, self).__init__()self.fc1 = nn.Linear(28 * 28, 256)self.fc2 = nn.Linear(256, 64)self.fc3 = nn.Linear(64, 10)def forward(self, x):x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return xnet = Net()
# [w1, b1, w2, b2, w3, b3]
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
train_loss = []for epoch in range(3):for batch_idx, (x, y) in enumerate(train_loader):x = x.view(x.size(0), 28*28)out = net(x)y_onehot = one_hot(y)loss = F.mse_loss(out, y_onehot)optimizer.zero_grad()loss.backward()optimizer.step()train_loss.append(loss.item())if batch_idx % 10==0:print(epoch, batch_idx, loss.item())plot_curve(train_loss)total_correct = 0
for x,y in test_loader:x  = x.view(x.size(0), 28*28)out = net(x)pred = out.argmax(dim=1)correct = pred.eq(y).sum().float().item()total_correct += correcttotal_num = len(test_loader.dataset)
acc = total_correct / total_num
print('test acc:', acc)x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28*28))
pred = out.argmax(dim=1)
plot_image(x, pred, 'test')
http://www.tj-hxxt.cn/news/62421.html

相关文章:

  • 网站服务器平台佛山网站优化排名推广
  • 微信官方网站是多少钱搜索引擎优化指南
  • 改变关键词对网站的影响找相似图片 识别
  • b2b网站推广方案怎么写新产品推广方式有哪些
  • 网站搭建价格表防城港网站seo
  • wordpress 影楼seo免费推广
  • 莱芜金点子信息港最新招聘人才qq群排名优化
  • 做网站的图片是怎么做的网站服务器搭建
  • 家具网站开发设计任务书与执行方案手机怎么做网站
  • 做资讯网站怎么挣钱百度云盘网页版
  • 网络营销网站的建设与策划seo 优化一般包括哪些内容
  • 织梦网站如何做二级导航企业网站推广渠道
  • 破解asp网站后台地址新闻头条
  • 买好域名之后怎么做网站aso优化师工作很赚钱吗
  • 网站内部链接的策略国内真正的免费建站
  • 随意设计一个网站百度高级搜索技巧
  • 做网站可以干什么东莞关键词seo优化
  • 单片机编程入门基础知识seo内部优化包括哪些内容
  • 网站建设投标文件怎样推广自己的网站
  • 2019做哪个网站赚钱磁力搜索器下载
  • 策划公司起什么名字好电子商务seo
  • 免费的seo优化工具seo公司
  • 网站开发学习流程图地推团队去哪里找
  • 全球电子商务网站排名seo整站优化服务教程
  • 政府网站群建设的好处微营销推广平台有哪些
  • 网页设计与网站建设报告天津搜索引擎seo
  • 杭州网站制作建设正规app推广
  • 个人seo怎么赚钱优化师是一份怎样的工作
  • 电脑网站做名片做企业网站建设的公司
  • 手机网站模板 psd怎么安装百度