从零和使用mxnet实现线性回归

1.线性回归从零实现(1000,)epoch:1,loss:5.7996epoch:2,loss:2.1903epoch:3,loss:0.9078epoch:4,loss:0.3178e

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

1.线性回归从零实现

from mxnet import ndarray as nd
import matplotlib.pyplot as plt
import numpy as np
import time
num_inputs = 2
num_examples = 1000
w = [2,-3.4]
b = 4.2

x = nd.random.normal(scale=1,shape=(num_examples,num_inputs))
y = nd.dot(x,nd.array(w).T) + b
y += nd.random.normal(scale=0.01,shape=y.shape)
print(y.shape)
(1000,)
plt.scatter(x[:,1].asnumpy(),y.asnumpy())
plt.show()

从零和使用mxnet实现线性回归

class LinearRegressor:
    def __init__(self,input_shape,output_shape):
        self.input_shape = input_shape
        self.output_shape = output_shape
        self.weight = nd.random.normal(scale=0.01,shape=(input_shape,1))
        self.bias = nd.zeros(shape=(1))

    def fit(self,x,y,learning_rate,epoches,batch_size):
        start = time.time()
        for epoch in range(epoches):
            for batch_data in self.batches(x,y,batch_size):
                x_batch,y_batch = batch_data[0],batch_data[1]
                y_hat = self.forward(x_batch)
                loss = self.mse(y_batch,y_hat)
                error = y_hat - y_batch.reshape(y_hat.shape)
                self.optimizer(x_batch,error,learning_rate)
            print('epoch:{},loss:{:.4f}'.format(epoch+1,self.mse(y,self.forward(x)).asscalar()))
        print('weight:',self.weight)
        print('bias:',self.bias)
        print('time interval:{:.2f}'.format(time.time() - start))
        
    def forward(self,x):
        return nd.dot(x,self.weight) + self.bias
    
    def mse(self,y,y_hat):
        m = len(y)
        mean_square = nd.sum((y - y_hat.reshape(y.shape)) ** 2) / (2 * m)
        return mean_square
    
    def optimizer(self,x,error,learning_rate):
        gradient = 1/len(x) * nd.dot(x.T,error)
        self.weight = self.weight - learning_rate * gradient
        self.bias = self.bias - learning_rate * error[0]
        
    def batches(self,x,y,batch_size):
        nSamples = len(x)
        nBatches = nSamples // batch_size 
        indexes = np.random.permutation(nSamples)
        for i in range(nBatches):
            yield (x[indexes[i*batch_size:(i+1)*batch_size]], y[indexes[i*batch_size:(i+1)*batch_size]])
        
lr = LinearRegressor(input_shape=2,output_shape=1)
lr.fit(x,y,learning_rate=0.1,epoches=20,batch_size=200)
epoch:1,loss:5.7996
epoch:2,loss:2.1903
epoch:3,loss:0.9078
epoch:4,loss:0.3178
epoch:5,loss:0.0795
epoch:6,loss:0.0204
epoch:7,loss:0.0156
epoch:8,loss:0.0068
epoch:9,loss:0.0022
epoch:10,loss:0.0009
epoch:11,loss:0.0003
epoch:12,loss:0.0001
epoch:13,loss:0.0001
epoch:14,loss:0.0001
epoch:15,loss:0.0000
epoch:16,loss:0.0000
epoch:17,loss:0.0000
epoch:18,loss:0.0001
epoch:19,loss:0.0001
epoch:20,loss:0.0001
weight: 
[[ 1.999662]
 [-3.400079]]
<NDArray 2x1 @cpu(0)>
bias: 
[4.2030163]
<NDArray 1 @cpu(0)>
time interval:0.22

2.线性回归简洁实现

from mxnet import gluon
from mxnet.gluon import loss as gloss
from mxnet.gluon import data as gdata
from mxnet.gluon import nn
from mxnet import init,autograd

# 定义模型
net = nn.Sequential()
net.add(nn.Dense(1))

# 初始化模型参数
net.initialize(init.Normal(sigma=0.01))

# 定义损失函数
loss = gloss.L2Loss()

# 定义优化算法
optimizer = gluon.Trainer(net.collect_params(), 'sgd',{'learning_rate':0.1})

epoches = 20
batch_size = 200

# 获取批量数据
dataset = gdata.ArrayDataset(x,y)
data_iter = gdata.DataLoader(dataset,batch_size,shuffle=True)

# 训练模型
start = time.time()
for epoch in range(epoches):
    for batch_x,batch_y in data_iter:
        with autograd.record():
            l = loss(net(batch_x),batch_y)
        l.backward()
        optimizer.step(batch_size)
    l = loss(net(x),y)
    print('epoch:{},loss:{:.4f}'.format(epoch+1,l.mean().asscalar()))
print('weight:',net[0].weight.data())
print('weight:',net[0].bias.data())
print('time interval:{:.2f}'.format(time.time() - start))
epoch:1,loss:5.7794
epoch:2,loss:1.9934
epoch:3,loss:0.6884
epoch:4,loss:0.2381
epoch:5,loss:0.0825
epoch:6,loss:0.0286
epoch:7,loss:0.0100
epoch:8,loss:0.0035
epoch:9,loss:0.0012
epoch:10,loss:0.0005
epoch:11,loss:0.0002
epoch:12,loss:0.0001
epoch:13,loss:0.0001
epoch:14,loss:0.0001
epoch:15,loss:0.0001
epoch:16,loss:0.0000
epoch:17,loss:0.0000
epoch:18,loss:0.0000
epoch:19,loss:0.0000
epoch:20,loss:0.0000
weight: 
[[ 1.9996439 -3.400059 ]]
<NDArray 1x2 @cpu(0)>
weight: 
[4.2002025]
<NDArray 1 @cpu(0)>
time interval:0.86

3. 附:mxnet中的损失函数核初始化方法

  • 损失函数

    all = [‘Loss’, ‘L2Loss’, ‘L1Loss’,
    ‘SigmoidBinaryCrossEntropyLoss’, ‘SigmoidBCELoss’,
    ‘SoftmaxCrossEntropyLoss’, ‘SoftmaxCELoss’,
    ‘KLDivLoss’, ‘CTCLoss’, ‘HuberLoss’, ‘HingeLoss’,
    ‘SquaredHingeLoss’, ‘LogisticLoss’, ‘TripletLoss’, ‘PoissonNLLLoss’, ‘CosineEmbeddingLoss’]

  • 初始化方法

    [‘Zero’, ‘One’, ‘Constant’, ‘Uniform’, ‘Normal’, ‘Orthogonal’,’Xavier’,’MSRAPrelu’,’Bilinear’,’LSTMBias’,’DusedRNN’]

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/120006.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Clover 引导器.配置助手[通俗易懂]

    Clover引导器.配置助手.Yosemite版块.更新贴Beta2.0为了让各位下载更方便本帖不设置回帖可见希望路过的朋友帮顶有需要的朋友顶个帖让更多后来者们看见提取码[编译PKG]py81[编译EFI+boot1h2]8ctu[编译ISO]zq9f首先向Clover开发人员致敬:Slice,withhelpofKabyl,

    2022年4月10日
    33
  • 什么叫一层交换机,二层交换机,三层交换机?

    什么叫一层交换机,二层交换机,三层交换机?

    2021年12月1日
    103
  • SpringBoot启动全流程源码解析(超详细版)[通俗易懂]

    SpringBoot启动全流程源码解析(超详细版)[通俗易懂]我们在使用SpringBoot启动项目的时候,可能只需加一个注解,然后启动main,整个项目就运行了起来,但事实真的是所见即所得吗,还是SpringBoot在背后默默做了很多?本文会通过源码解析的方式深入理解SpringBoot启动全过程SpringBoot启动过程流程图源码解析大家不要抗拒源码解析,这个非常优秀的代码,我们如果能够学会对自己代码编写水平大有裨益首先,我们先来看下SpringBoot项目的启动类@SpringBootApplicationpublicclassSp.

    2022年9月11日
    1
  • 概率论中 PDF,PMF,CDF的含义[通俗易懂]

    概率论中 PDF,PMF,CDF的含义[通俗易懂]概率论中PDF,PMF,CDF的含义在概率论中,我们经常能碰到这样几个概念PDF,PMF,CDF,这里就简单介绍一下PDF:概率密度函数(probabilitydensityfunction),在数学中,连续型随机变量的概率密度函数(在不至于混淆时可以简称为密度函数)是一个描述这个随机变量的输出值,在某个确定的取值点附近的可能性的函数。概率密度函数都是针对连续性随机变量的,对于连续性随机变量,都是针对某一段区间的取值,在一个点的取值都是几乎为0的,所以我们研究连续性随机变量时,都是取变量在一段

    2022年5月24日
    71
  • 滚动条的scroll属性(怎么修改滚动条样式)

    http://www.dengjie.com/temp/scroller.swfIE下的滚动条样式IE是最早提供滚动条的样式支持,好多年了,但是其它浏览器一直没有支持,IE独孤求败了。这些样式规则很简单:scrollbar-arrow-color:color;/*三角箭头的颜色*/scrollbar-face-color:color;/*立体滚动条的颜色(包

    2022年4月15日
    162
  • 使用adb安装apk命令格式

    使用adb安装apk命令格式adbinstall[-r][-s]-r表示重新安装APK包,-s表示将APK包安装到SD卡上adbinstall[-k]-k表示只删除应用程序,但保留该程序所用的数据和缓存目录

    2022年5月18日
    45

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号