增加肌肉记忆,码一遍 龙哥的pytorch示例: ex_001, matMul;ex_002, autograd;ex_003, 线性函数的 gradient descent <梯度下降最简示例>

2023-10-28

import torch
import time

print(torch.__version__)
print(torch.cuda.is_available())

a = torch.randn(1024*8*16, 1000)
b = torch.randn(1000, 2000)

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print(a.device, t1-t0, c.norm(2))

device = torch.device('cuda')
a = a.to(device)
b = b.to(device)

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2-t0, c.norm(2))

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2-t0, c.norm(2))

save as helloMatMul_cpu_gpu_time.py

$ python3 ./helloMatMul_cpu_gpu_time.py

output:


helloPytorch# python3 ./helloTorch.py
1.9.0a0+2ecb2c7
True
cpu 0.6934514045715332 tensor(507455.8750)
cuda:0 0.5243451595306396 tensor(512158.1562, device='cuda:0')
cuda:0 0.001405954360961914 tensor(512158.1562, device='cuda:0')

计算 A(1024*8*16  x  1000)   *     B(1000 x 2000):

cpu 运行时间

gpu warming up 时间

gpu running time

—以下为—ex_002 autograd—————————————————————————————

import torch
from torch import autograd


x = torch.tensor(1.)
a = torch.tensor(1., requires_grad=True)
b = torch.tensor(2., requires_grad=True)
c = torch.tensor(3., requires_grad=True)

y = a**2 * x + b* x + c

#print('before0:', grads[0], grads[1], grads[2])
print('before:', a.grad, b.grad, c.grad)
grads = autograd.grad(y, [a, b, c])
print('after:', grads[0], grads[1], grads[2])
print('after2:', a.grad, b.grad, c.grad)

save as helloAutograd.py

output:

helloPytorch# python3 ./helloAutograd.py
before: None None None
after: tensor(2.) tensor(1.) tensor(1.)
after2: None None None

预先 a = 1., b = 2.,c = 3., x=1.

将系数视为待定的变量,训练的对象,对a,b,c 分别自动求导,结果为 2,1, 1

———ex_003—linear regression————————————————————————

代码:

import numpy as np

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


def step_gradient(b_current, w_current, points, learningRate):
    b_gradient = 0
    w_gradient = 0
    N = float(len(points))
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        b_gradient += -(2/N) * (y - ((w_current*x) + b_current))
        w_gradient += -(2/N) * x * (y - ((w_current*x)+ b_current))

    new_b = b_current - (learningRate * b_gradient)
    new_w = w_current - (learningRate * w_gradient)
    return [new_b, new_w]

def gradient_descent_runner(points, starting_b, starting_w, 
                            learning_rate, num_iterations):
    b = starting_b
    w = starting_w
    for i in range(num_iterations):
        b, w = step_gradient(b, w, np.array(points), learning_rate)
    return [b, w]

def run():
    points = np.genfromtxt("randData.csv", delimiter=",")
    learning_rate = 0.00001
    initial_b = 0
    initial_w = 0
    num_iterations = 1000000
    print("Starting gradient descent at b = {0}, w = {1}, error = {2}"
            .format(initial_b, initial_w,
                    compute_error_for_line_given_points(initial_b, initial_w, points))
          )
    print("Running...")
    [b, w] = gradient_descent_runner(points, initial_b, initial_w, learning_rate, num_iterations)
    print("After {0} iterations learning_rate = {1}, b = {2} w = {3}, error = {4}"
            .format(num_iterations, learning_rate, b, w, 
                    compute_error_for_line_given_points(b, w, points))
         )

if __name__ == '__main__':
    run()

data file:

save as randData.csv

32.502345269453031,31.70700584656992
53.426804033275019,68.77759598163891
61.530358025636438,62.562382297945803
47.475639634786098,71.546632233567777
59.813207869512318,87.230925133687393
55.142188413943821,78.211518270799232
52.211796692214001,79.64197304980874
39.299566694317065,59.171489321869508
48.10504169176825,75.331242297063056
52.550014442733818,71.300879886850353
45.419730144973755,55.165677145959123
54.351634881228918,82.478846757497919
44.164049496773352,62.008923245725825
58.16847071685779,75.392870425994957
56.727208057096611,81.43619215887864
48.955888566093719,60.723602440673965
44.687196231480904,82.892503731453715
60.297326851333466,97.379896862166078
45.618643772955828,48.847153317355072
38.816817537445637,56.877213186268506
66.189816606752601,83.878564664602763
65.41605174513407,118.59121730252249
47.48120860786787,57.251819462268969
41.57564261748702,51.391744079832307
51.84518690563943,75.380651665312357
59.370822011089523,74.765564032151374
57.31000343834809,95.455052922574737
63.615561251453308,95.229366017555307
46.737619407976972,79.052406169565586
50.556760148547767,83.432071421323712
52.223996085553047,63.358790317497878
35.567830047746632,41.412885303700563
42.436476944055642,76.617341280074044
58.16454011019286,96.769566426108199
57.504447615341789,74.084130116602523
45.440530725319981,66.588144414228594
61.89622268029126,77.768482417793024
33.093831736163963,50.719588912312084
36.436009511386871,62.124570818071781
37.675654860850742,60.810246649902211
44.555608383275356,52.682983366387781
43.318282631865721,58.569824717692867
50.073145632289034,82.905981485070512
43.870612645218372,61.424709804339123
62.997480747553091,115.24415280079529
32.669043763467187,45.570588823376085
40.166899008703702,54.084054796223612
53.575077531673656,87.994452758110413
33.864214971778239,52.725494375900425
64.707138666121296,93.576118692658241
38.119824026822805,80.166275447370964
44.502538064645101,65.101711570560326
40.599538384552318,65.562301260400375
41.720676356341293,65.280886920822823
51.088634678336796,73.434641546324301
55.078095904923202,71.13972785861894
41.377726534895203,79.102829683549857
62.494697427269791,86.520538440347153
49.203887540826003,84.742697807826218
41.102685187349664,59.358850248624933
41.182016105169822,61.684037524833627
50.186389494880601,69.847604158249183
52.378446219236217,86.098291205774103
50.135485486286122,59.108839267699643
33.644706006191782,69.89968164362763
39.557901222906828,44.862490711164398
56.130388816875467,85.498067778840223
57.362052133238237,95.536686846467219
60.269214393997906,70.251934419771587
35.678093889410732,52.721734964774988
31.588116998132829,50.392670135079896
53.66093226167304,63.642398775657753
46.682228649471917,72.247251068662365
43.107820219102464,57.812512976181402
70.34607561504933,104.25710158543822
44.492855880854073,86.642020318822006
57.50453330326841,91.486778000110135
36.930076609191808,55.231660886212836
55.805733357942742,79.550436678507609
38.954769073377065,44.847124242467601
56.901214702247074,80.207523139682763
56.868900661384046,83.14274979204346
34.33312470421609,55.723489260543914
59.04974121466681,77.634182511677864
57.788223993230673,99.051414841748269
54.282328705967409,79.120646274680027
51.088719898979143,69.588897851118475
50.282836348230731,69.510503311494389
44.211741752090113,73.687564318317285
38.005488008060688,61.366904537240131
32.940479942618296,67.170655768995118
53.691639571070056,85.668203145001542
68.76573426962166,114.85387123391394
46.230966498310252,90.123572069967423
68.319360818255362,97.919821035242848
50.030174340312143,81.536990783015028
49.239765342753763,72.111832469615663
50.039575939875988,85.232007342325673
48.149858891028863,66.224957888054632
25.128484647772304,53.454394214850524

改变学习率或学习次数后的 output:


root@defdc4d0972f:/home/yy/ex/pytorchTest/helloPytorch# python3 ./linearRegression.py
Starting gradient descent at b = 0, w = 0, error = 5565.107834483211
Running...
After 1000 iterations learning_rate = 0.0001, b = 0.08893651993741346 w = 1.4777440851894448, error = 112.61481011613473
root@defdc4d0972f:/home/yy/ex/pytorchTest/helloPytorch# python3 ./linearRegression.py
Starting gradient descent at b = 0, w = 0, error = 5565.107834483211
Running...
After 100000 iterations learning_rate = 1e-05, b = 0.6078967069728876 w = 1.4675440808343854, error = 112.3153353259074
root@defdc4d0972f:/home/yy/ex/pytorchTest/helloPytorch# python3 ./linearRegression.py
Starting gradient descent at b = 0, w = 0, error = 5565.107834483211
Running...
After 1000000 iterations learning_rate = 1e-05, b = 4.24797484458317 w = 1.395999454129054, error = 110.78632200941048
root@defdc4d0972f:/home/yy/ex/pytorchTest/helloPytorch#

loss值越小,b的值越大的。主要是因为数据集距离原点有点远,斜率w的一点点变化,就明显影响b的值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

增加肌肉记忆,码一遍 龙哥的pytorch示例: ex_001, matMul;ex_002, autograd;ex_003, 线性函数的 gradient descent <梯度下降最简示例> 的相关文章

随机推荐

  • 数据清洗实例分析

    一 数据清洗工作 数据清洗 如填充缺失数据 消除噪声数据等 主要是通过分析 脏数据 的产生原因和存在形式 利用现有的数据挖掘手段和方法去清洗 脏数据 将 脏数据 转化为满足数据质量要求或应用要求的数据 从而提高数据集的质量 满足现阶段数据分
  • 【贪心+可并堆】 [BalticOI 2004]Sequence 数字序列

    题目 思路 首先考虑原题弱化版 相邻的b可以相等 于是我们可以得到两个性感感性的结论 如果a递增 则b a最优 如果a递减 b a的中位数最优 根据这两个结论 我们可以得到一个比较感性的做法 将原序列分成单调不升的m段 则每一段我们都取中位
  • 1122.数组的相对排序(分治+拼接)

    题意 本题目刚刚接触可能会有一点想不通 这是正常的现象对题目的解释如下 arr1的数组与arr2的数组中以arr2的数组进行排序 将arr1中的但是没有在arr2中不存在的元素 与arr2进行拼接 原题题干 代码 class Solutio
  • PostgreSQL数据库命令行执行SQL脚本的三种方式

    文章目录 前言 一 psql命令执行 二 i命令执行 三 e命令执行 总结 前言 生成环境中 出于安全性等原因 往往不提供数据库连接工具 所以对数据库的更新和升级就得通过命令行来实现 本文总结了三种命令行执行sql脚本的方式 一 psql命
  • 22.1 Numpy 去重

    Numpy 去重 np unique 参数1 a 数组 参数2 return index True False 新列表元素在旧列表中的位置 参数3 retun inverse True False 旧列表元素在新列表中的位置 参数4 ret
  • Vue3 实现Event-Bus事件总线 (mitt插件)

    文章目录 一 参考 二 问题描述 三 开发案例 typescript 解析 instance proxy Bus出错 一 参考 vue3 eventBus npm mitt 二 问题描述 Vue3 没有像Vue2那样创建一个Vue实例作为事
  • centos 7 开启80,443端口

    一 查看系统防火墙状态 如果返回 running 代表防火墙启动正常 1 firewall cmd state 二 开启端口外网访问 1 添加端口 返回 success 代表成功 permanent永久生效 没有此参数重启后失效 1 fir
  • QProcess中的调用外部exe结束之后的finished信号及常用信号

    1 可以参考相关的链接 https doc qt io Qt 5 qprocess html finished 2 注意使用的时候启动以下4个信号 使用的是start 否则启动就有问题 这边注意一下start 和startDetached
  • 【总结】Apk反编译全解

    实践总结 解决问题 乐在分享 古月大仙荣誉出品 欢迎关注 加粉 点赞 评论 交流 1 内容摘要 Apk保险措施 混淆 加固 NDK 敏感操作的字符串替代 检查签名 高手成长路径 脱壳 反编译 jadx dex jar和apktool xml
  • 安装WSL过程

    1 准备 必须使用windows10 2004版本和更高的版本 19041或者更高 或者windows11 win R 输入winver查询当前windows版本 2 安装 现在可以通过在命令行 管理员权限 输入wsl install 来安
  • Pikachu-暴力破解验证码绕过

    目录 一 验证码绕过 on client 1 验证码的认证流程 2 不安全验证码 on client常见问题 3 实验过程 二 验证码绕过 on server 1 不安全验证码 on server常见问题 2 实验过程 一 验证码绕过 on
  • MySQL存储过程

    文章目录 简介 优点 缺点 编写第一个MySQL存储过程 调用存储过程要调用存储过程 可以使用以下SQL命令 MySQL存储过程的变量 声明变量 分配变量值 变量范围 作用域 删除存储过程 存储过程的参数 MySQL存储过程参数示例 1 I
  • 【开发工具】使用VMware安装Ubuntu系统

    目录 一 下载Ubuntu镜像 二 下载VMware虚拟机系统 三 新建虚拟机 四 安装Ubuntu系统 一 下载Ubuntu镜像 下载地址 版本 Ubuntu 22 04 LTS https cn ubuntu com download
  • "通配符"和"正则表达式"的区别

    通配符是系统level的 而正则表达式需要相关工具的支持 egrep awk vi perl 在文本过滤工具里 都是用正则表达式 比如像awk sed等 是针对文件的内容的 通配符多用在文件名上 比如查找find ls cp 等等 1 通配
  • ipad连接电脑_一个从windows传文件到ipad的方法

    动机 写这篇文章的起因是想用ipad看存在windows上的视频 于是就琢磨了下windows系统传文件到ipad的方法 一个比较好的办法是用iCloud传 但是条件受限 一方面 iCloud只有5G的存储空间 另一方面 家里没网 只能靠4
  • 技术溢出

    1 企业和国家都是一个虚拟的主题 是由人们的想象构成 2 国家只是在体量 多样性上高于企业而已 3 管理企业和管理国家理论上没有区别 只是使命感不同 企业是为了盈利而产生的 政党是为了人民而服务的 后来有的企业开始服务于人民 有的政党开始逐
  • Linux必学知识(超全)

    Linux 一 Linux 的介绍 二 CentOS 安装技术难点 网络配置三种方式理解 2 1虚拟机的三种网络配置方式的说明 2 2 Centos 终端的使用和联网 2 2 1在 centos 的 ff 可以联网 可以和外部的 ip 联通
  • 【尚硅谷-Java学习】回形数

    回形数 题目描述 输入整数n 生成n n的二维数组 元素按照顺时针顺序从1递增 例如输入3 得到 1 2 3 8 9 4 7 6 5 思路 定义四个变量up down left right 分别表示数组的最上面 最下面 最左 最右的索引 从
  • 第十四届蓝桥杯(第二期)模拟赛试题与题解 C++

    第十四届蓝桥杯 第二期 模拟赛试题与题解 C 试题A 题解 位运算 试题B 题解 闰年判断 试题C 题解 枚举判断 试题D 题解 动态规划 问题E 题解 记忆化搜索 试题F 题解 计算 试题G 题解 哈希集合 试题H 题解 后缀回文 试题I
  • 增加肌肉记忆,码一遍 龙哥的pytorch示例: ex_001, matMul;ex_002, autograd;ex_003, 线性函数的 gradient descent <梯度下降最简示例>

    import torch import time print torch version print torch cuda is available a torch randn 1024 8 16 1000 b torch randn 10