机器学习(ml)系列一之linearregression

jaww jaww     2023-04-19     350

关键词:

一、线性回归

1、模型

技术图片

 

 2、损失函数

技术图片

 

 3、优化函数-梯度下降

技术图片

 

#!/usr/bin/env python
# coding: utf-8
import torch
import time

# init variable a, b as 1000 dimension vector
n = 1000
a = torch.ones(n)
b = torch.ones(n)

# define a timer class to record time class Timer(object): """Record multiple running times.""" def __init__(self): self.times = [] self.start() def start(self): # start the timer self.start_time = time.time() def stop(self): # stop the timer and record time into a list self.times.append(time.time() - self.start_time) return self.times[-1] def avg(self): # calculate the average and return return sum(self.times)/len(self.times) def sum(self): # return the sum of recorded time return sum(self.times)
timer = Timer() c = torch.zeros(n) for i in range(n): c[i] = a[i] + b[i] ‘%.5f sec‘ % timer.stop() timer.start() d = a + b ‘%.5f sec‘ % timer.stop() # import packages and modules get_ipython().run_line_magic(‘matplotlib‘, ‘inline‘) import torch from IPython import display from matplotlib import pyplot as plt import numpy as np import random print(torch.__version__) # ### 线性回归模型从零开始的实现 # set input feature number num_inputs = 2 # set example number num_examples = 1000 # set true weight and bias in order to generate corresponded label true_w = [2, -3.4] true_b = 4.2 features = torch.randn(num_examples, num_inputs, dtype=torch.float32) labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float32) # ### 使用图像来展示生成的数据 plt.scatter(features[:, 1].numpy(), labels.numpy(), 1); # ### 读取数据集 def data_iter(batch_size, features, labels): num_examples = len(features) indices = list(range(num_examples)) random.shuffle(indices) # random read 10 samples for i in range(0, num_examples, batch_size): j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch yield features.index_select(0, j), labels.index_select(0, j) batch_size = 10 for X, y in data_iter(batch_size, features, labels): print(X, ‘ ‘, y) break # ### 模型初始化 w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32) b = torch.zeros(1, dtype=torch.float32) w.requires_grad_(requires_grad=True) b.requires_grad_(requires_grad=True) # ### 定义模型 # 定义用来训练参数的训练模型: # $$ mathrmprice = w_mathrmarea cdot mathrmarea + w_mathrmage cdot mathrmage + b $$ # In[19]: def linreg(X, w, b): return torch.mm(X, w) + b # ### 定义损失函数 # 我们使用的是均方误差损失函数: # $$l^(i)(mathbfw, b) = frac12 left(haty^(i) - y^(i) ight)^2,$$ # In[16]: def squared_loss(y_hat, y): return (y_hat - y.view(y_hat.size())) ** 2 / 2 # ### 定义优化函数 # 在这里优化函数使用的是小批量随机梯度下降: # $$(mathbfw,b) leftarrow (mathbfw,b) - fraceta|mathcalB| sum_i in mathcalB partial_(mathbfw,b) l^(i)(mathbfw,b)$$ # In[17]: def sgd(params, lr, batch_size): for param in params: param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track # ### 训练 # 当数据集、模型、损失函数和优化函数定义完了之后就可来准备进行模型的训练了。 # In[20]: # super parameters init lr = 0.03 num_epochs = 5 net = linreg loss = squared_loss # training for epoch in range(num_epochs): # training repeats num_epochs times # in each epoch, all the samples in dataset will be used once # X is the feature and y is the label of a batch sample for X, y in data_iter(batch_size, features, labels): l = loss(net(X, w, b), y).sum() # calculate the gradient of batch sample loss l.backward() # using small batch random gradient descent to iter model parameters sgd([w, b], lr, batch_size) # reset parameter gradient w.grad.data.zero_() b.grad.data.zero_() train_l = loss(net(features, w, b), labels) print(‘epoch %d, loss %f‘ % (epoch + 1, train_l.mean().item())) # In[21]: w, true_w, b, true_b # ### 线性回归模型使用pytorch的简洁实现 # In[22]: import torch from torch import nn import numpy as np torch.manual_seed(1) print(torch.__version__) torch.set_default_tensor_type(‘torch.FloatTensor‘) # ### 生成数据集 # 在这里生成数据集跟从零开始的实现中是完全一样的。 # In[23]: num_inputs = 2 num_examples = 1000 true_w = [2, -3.4] true_b = 4.2 features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float) labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float) # ### 读取数据集 # In[24]: import torch.utils.data as Data batch_size = 10 # combine featues and labels of dataset dataset = Data.TensorDataset(features, labels) # put dataset into DataLoader data_iter = Data.DataLoader( dataset=dataset, # torch TensorDataset format batch_size=batch_size, # mini batch size shuffle=True, # whether shuffle the data or not num_workers=2, # read data in multithreading ) # In[27]: for X, y in data_iter: print(X, ‘ ‘, y) break # ### 定义模型 # In[28]: class LinearNet(nn.Module): def __init__(self, n_feature): super(LinearNet, self).__init__() # call father function to init self.linear = nn.Linear(n_feature, 1) # function prototype: `torch.nn.Linear(in_features, out_features, bias=True)` def forward(self, x): y = self.linear(x) return y net = LinearNet(num_inputs) print(net) # In[29]: # ways to init a multilayer network # method one net = nn.Sequential( nn.Linear(num_inputs, 1) # other layers can be added here ) # method two net = nn.Sequential() net.add_module(‘linear‘, nn.Linear(num_inputs, 1)) # net.add_module ...... # method three from collections import OrderedDict net = nn.Sequential(OrderedDict([ (‘linear‘, nn.Linear(num_inputs, 1)) # ...... ])) print(net) print(net[0]) # ### 初始化模型参数 # In[30]: from torch.nn import init init.normal_(net[0].weight, mean=0.0, std=0.01) init.constant_(net[0].bias, val=0.0) # or you can use `net[0].bias.data.fill_(0)` to modify it directly # In[31]: for param in net.parameters(): print(param) # ### 定义损失函数 # In[32]: loss = nn.MSELoss() # nn built-in squared loss function # function prototype: `torch.nn.MSELoss(size_average=None, reduce=None, reduction=‘mean‘)` # ### 定义优化函数 # In[33]: import torch.optim as optim optimizer = optim.SGD(net.parameters(), lr=0.03) # built-in random gradient descent function print(optimizer) # function prototype: `torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, nesterov=False)` # In[34]: ##trainning num_epochs = 3 for epoch in range(1, num_epochs + 1): for X, y in data_iter: output = net(X) l = loss(output, y.view(-1, 1)) optimizer.zero_grad() # reset gradient, equal to net.zero_grad() l.backward() optimizer.step() print(‘epoch %d, loss: %f‘ % (epoch, l.item())) # In[35]: # result comparision dense = net[0] print(true_w, dense.weight.data) print(true_b, dense.bias.data) # In[ ]:

  

机器学习系列-tensorflow-03-线性回归linearregression(代码片段)

利用tensorflow实现数据的线性回归导入相关库importtensorflowastfimportnumpyimportmatplotlib.pyplotaspltrng=numpy.random参数设置learning_rate=0.01training_epochs=1000display_step=50训练数据train_X=numpy.asarray([3.3,4.4,5.5,6.7 查看详情

机器学习1linearregression作业

这个线性回归的作业需要上传到https://inclass.kaggle.com/c/ml2016-pm2-5-prediction上面,这是一个kaggle比赛的网站。第一次接触听说这个东西,恰好在京东上有一本刚出来的关于这个的书《Python机器学习及实践:从零开始通往Kaggle竞赛之... 查看详情

机器学习1linearregression作业

话说学机器学习,不写代码就太扯淡了。好了,接着上一次的线性回归作业。hw1作业的链接在这: http://speech.ee.ntu.edu.tw/~tlkagk/courses/ML_2016/Lecture/hw1.pdf 作业是预测台湾的PM2.5的指数,既然是回归问题,肯定是用的是上一节... 查看详情

系列ml.net学习篇——初识机器学习

由于公司项目涉及到机器学习和图像识别,虽然我并不是算法专家,但毕竟需要了解和知道其运转原理,因此自我进行了学习进化,决定在机器学习上有所进展,结合.NET技术的ML.NET,把机器学习的技能提升一个Level&#... 查看详情

系列ml.net学习篇——初识机器学习(代码片段)

由于公司项目涉及到机器学习和图像识别,虽然我并不是算法专家,但毕竟需要了解和知道其运转原理,因此自我进行了学习进化,决定在机器学习上有所进展,结合.NET技术的ML.NET,把机器学习的技能提升一个Level&#... 查看详情

机器学习方法:回归:线性回归linearregression

...周期会比較长。由于我还想写一些其它的,呵呵。content:linearregression,Ridge,LassoLogisticRegression,SoftmaxKmeans,GMM,E 查看详情

机器学习技术系列:一篇图文笔记了解机器学习基础知识

导言最近有小半年由近半数工作和生活时间在机器学习技术(ML)的学习与工程实践中,感觉自己阅读了几本ML方面好书,找到了一些更好的学习网站,所以重新梳理了一下自己理解的的ML基础知识。相关参考摘录书籍及网站如下... 查看详情

系列ml.net学习篇——初识机器学习(代码片段)

由于公司项目涉及到机器学习和图像识别,虽然我并不是算法专家,但毕竟需要了解和知道其运转原理,因此自我进行了学习进化,决定在机器学习上有所进展,结合.NET技术的ML.NET,把机器学习的技能提升一个Level&#... 查看详情

机器学习入门

...频:偏理论推导:B站白板推导;白板系列笔记DataWhale:机器学习实践代码李宏毅《机器学习/深度学习》2021课程(国语版本);在线笔记书籍书籍推荐包括:西瓜书,公式推导南瓜书;机器学习方法(李航)深度学习深度学习是基于... 查看详情

机器学习笔记-1linearregression(week1)

 1.LinearRegressionwithOnevariableLinearRegressionissupervisedlearning algorithm,Becausethedatasetisgivenarightanswerforeachexample.Andwearepredictingreal-valuedoutputsoitisaregressionproble 查看详情

ml:mlops系列讲解之《基于ml的软件的三个层次》解读

...略ML/AI迅速被新的应用程序和行业采用。如前所述,机器学习项目的目标是利用收集到的数据并应用机器学习算 查看详情

从零单排入门机器学习:线性回归(linearregression)实践篇

   线性回归(linearregression)实践篇之前一段时间在coursera看了Andrewng的机器学习的课程,感觉还不错,算是入门了。这次打算以该课程的作业为主线,对机器学习基本知识做一下总结。小弟才学疏浅,如有错误。敬请... 查看详情

机器学习系列_机器学习路线图(附资料)

...有,转载请联系作者并注明出处1.引言也许你和这个叫『机器学习』的家伙一点也不熟,但是你 查看详情

机器学习1线性回归(linearregression)

立个flag,本人从今天正式开始学习机器学习(MachineLearning)选取的第一门课还是吴恩达(AndrewNg)的斯坦福大学公开课:机器学习课程,我打算从作业入手,结合课程进行学习,预计一共分为8... 查看详情

coursera机器学习linearregression线性回归的小项目(代码片段)

Matlab环境: 1.一元线性回归ex1.m  %%MachineLearningOnlineClass-Exercise1:LinearRegression%Instructions%------------%%Thisfilecontainscodethathelpsyougetstartedonthe%linearexercise.Youwillneedtoc 查看详情

机器学习sklearn监督学习回归算法线性回归linearregression(代码片段)

importnumpyasnpimportmatplotlib.pyplotaspltfromsklearnimportlinear_model#设置中文字体plt.rcParams['font.sans-serif']='SimHei'plt.rcParams['axes.unicode_minus']=False#设置自变量和因变 查看详情

机器学习基石:09linearregression

线性回归假设代价函数---均方误差最小化样本内代价函数只有满秩方阵才有逆矩阵线性回归算法流程线性回归算法是隐式迭代的线性回归算法泛化可能的保证线性分类是近似求解,线性回归是解析求解,线性分类中使用0/1误... 查看详情

机器学习入门系列01,introduction简介

...0170326ML01Introduction.html我们将要学习什么东东?什么是机器学习?有右边这样非常大的音频数据集,写程序来进行学习,然后可以输出音频“Hello”有右边这样非 查看详情