从零和使用mxnet实现线性回归
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()

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']
从零和使用mxnet实现线性回归的更多相关文章
- 从零和使用mxnet实现dropout
需求: 从零和使用mxnet实现dropout 数据集: 使用load_digits()手写数字数据集 要求: 使用1个掩藏层n_hidden1 = 36,激活函数为relu,损失函数为softmax ...
- 从零和使用mxnet实现softmax分类
1.softmax从零实现 from mxnet.gluon import data as gdata from sklearn import datasets from mxnet import n ...
- 从零单排入门机器学习:线性回归(linear regression)实践篇
线性回归(linear regression)实践篇 之前一段时间在coursera看了Andrew ng的机器学习的课程,感觉还不错,算是入门了. 这次打算以该课程的作业为主线,对机器学习基本知识做 ...
- MXNET:监督学习
线性回归 给定一个数据点集合 X 和对应的目标值 y,线性模型的目标就是找到一条使用向量 w 和位移 b 描述的线,来尽可能地近似每个样本X[i] 和 y[i]. 数学公式表示为\(\hat{y}=X ...
- ufldl学习笔记与编程作业:Linear Regression(线性回归)
ufldl学习笔记与编程作业:Linear Regression(线性回归) ufldl出了新教程,感觉比之前的好.从基础讲起.系统清晰,又有编程实践. 在deep learning高质量群里面听一些 ...
- SAS学习笔记23 线性回归、多元回归
线性回归 由样本资料计算的回归系数b和其他统计量一样,存在抽样误差,因此,需要对线性回归方程进行假设检验 1.方差分析 2.t检验 相关系数的假设检验 相关系数(correlation coeffic ...
- linger博客原创性博文导航
linger博客原创性博文导航 http://blog.csdn.net/lingerlanlan 大学研究游戏外挂技术開始了此博客.断断续续写了些博文. 后来,開始机器学习和深度学习的研究工作,因为 ...
- 深度学习中常见的 Normlization 及权重初始化相关知识(原理及公式推导)
Batch Normlization(BN) 为什么要进行 BN 防止深度神经网络,每一层得参数更新会导致上层的输入数据发生变化,通过层层叠加,高层的输入分布变化会十分剧烈,这就使得高层需要不断去重新 ...
- 基于MXNET框架的线性回归从零实现(房价预测为例)
1.基于MXNET框架的线性回归从零实现例子 下面博客是基于MXNET框架下的线性回归从零实现,以一个简单的房屋价格预测作为例子来解释线性回归的基本要素.这个应用的目标是预测一栋房子的售出价格(元). ...
随机推荐
- ElasticSearch : High Rest Api 使用
pom文件: <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId> ...
- 使用kibana给不同的用户创建不同的space
Elastic安全机制 在很多的情况下,出于安全的原因,我们需要对不同的Kibana用户分配不同的用户权限,这样使得他们之间不能互相访问彼此的资源,同 时他们也应该对不同的索引拥有不同的权限,比如读, ...
- html页面的渲染And<script>位置的影响
周末加班敲代码的时用到了<script>标签,突然想到了一个问题:别的自测项目里面<script>我把他放在了不同位置,这里应该会对代码的执行与渲染后影响吧?于是今天专门进行了 ...
- 【翻译】Tusdotnet中文文档(1)配置和用法
TUSDOTNET Tusdotnet是tus协议的一个dotnet实现.tus协议是用来规范文件上传的整个过程,tus基于http协议,规定了一些上传过程中的头部(headers)和对上传过程的描述 ...
- asp.net core流式上传大文件
asp.net core流式上传大文件 首先需要明确一点就是使用流式上传和使用IFormFile在效率上没有太大的差异,IFormFile的缺点主要是客户端上传过来的文件首先会缓存在服务器内存中,任何 ...
- Flask send_file request
send_file: send_file( filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, ...
- js生成一定范围内的随机整数
Math.floor(Math.random()*(m-n+1)+n) Math.floor(Math.random() * (50 - 1 + 1) + 1): 生成1-50内的随机整数
- 网页百度地图api,支持位置偏移
网页百度地图api,支持位置偏移 需加载 jq <style type="text/css"> #allmap {width:100%; height:100%; bo ...
- tp5.0在控制器中和在模板中调用配置文件中的常量
框架配置文件config.php中定义 'view_replace_str' => [ '__MEMBER__'=> '/static/member', '__uplo ...
- disable_function绕过--利用LD_PRELOAD
0x00 前言 有时候直接执行命令的函数被ban了,那么有几种思路可以bypass 1.使用php本身自带的能够调用外部程序的函数 2.使用第三方插件入(如imagick) 但是这两种无非就是利用ph ...