从零和使用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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • WPF教程三:布局之WrapPanel面板(转 )[通俗易懂]

    WPF教程三:布局之WrapPanel面板(转 )[通俗易懂]WPF教程三:布局之WrapPanel面板WrapPanel:环绕面板WrapPanel布局面板将各个控件从左至右按照行或列的顺序罗列,当长度或高度不够时就会自动调整进行换行,后续排序按照从上至下

    2022年7月1日
    32
  • StrictMode介绍[通俗易懂]

    StrictMode介绍[通俗易懂]第1页:  【IT168技术  】最新的Android平台中(Android2.3起),新增加了一个新的类,叫StrictMode(android.os.StrictMode)。这个类可以用来帮助开发者改进他们编写的应用,并且提供了各种的策略,这些策略能随时检查和报告开发者开发应用中存在的问题,比如可以监视那些本不应该在主线程中完成的工作或者其他的一些不规范和不好的代码。  Stri

    2022年5月1日
    65
  • stopwords.txt中英文数据集,四川大学机器智能实验室停用词库,哈工大停用词表,中文停用词表,百度停用词表百度网盘下载

    stopwords.txt中英文数据集,四川大学机器智能实验室停用词库,哈工大停用词表,中文停用词表,百度停用词表百度网盘下载今天找stopwords.txt数据集找了好长时间,真是气死了,好多都是需要金币,这数据集不是应该共享的么。故搜集了一些数据集,主要包括四川大学机器智能实验室停用词库,哈工大停用词表,中文停用词表,百度停用词表和一些其他的stopword.text。最后用python将这些数据集合并成一个完整的数据集stopword.txt。百度网盘地址在链接:https://pan.baidu.com/s/1KBkOzYk-wRYaWno6HSOE9g提取码:4sm6文件不是很大可以直接下载。下面是详细的目录。

    2022年6月24日
    26
  • windows安装gitblit[通俗易懂]

    windows安装gitblit[通俗易懂]1、Gitblit-Windows版下载gitblithttp://www.gitblit.com/目前最新版本为CurrentRelease1.8.0(2016-06-22)2、安装和配置gitblit解压gitblit-1.8.0.zip后,如图所示:修改data/defaults.properties #配置git仓库地址…

    2025年10月3日
    4
  • chrome frame使用记录「建议收藏」

    chrome frame使用记录「建议收藏」chromeframe使用记录参考:http://blog.csdn.net/xiaoyu411502/article/details/12619881http://www.cystc.org/?p=259…

    2022年7月16日
    18
  • F分布的概率密度函数_F分布的统计量是

    F分布的概率密度函数_F分布的统计量是定义:设X1∼χ2(m),X2∼χ2(n)X_{1}\sim\chi^{2}(m),X_{2}\sim\chi^{2}(n)X1​∼χ2(m),X2​∼χ2(n),X1X_{1}X1​与X2X_{2}X2​相互独立,则称随机变量F=X1/mX2/nF=\frac{X_{1}/m}{X_{2}/n}F=X2​/nX1​/m​服从自由度为mmm及nnn的FFF分布,mmm称为第一自由度,n\boldsymbol{n}n称为第二自由

    2022年10月10日
    3

发表回复

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

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