Pytorch中代码详解(学习笔记)

Pytorch中代码详解(学习笔记、持续更新中…)

记录此博客仅为参考和备忘

1.assert断言函数

assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假。用来测试表示式,其返回值为假,就会触发异常。

assert os.path.exists(root), "dataset root: {} does not exist.".format(root)
#os.path.exists(root)为false是执行逗号后语句
assert os.path.exists(json_path), json_path + " does not exist."

2.文件夹处理

#1.路径是否存在/返回布尔值
os.path.exists(root)
#2.os.path.操作
os.path.abspath(path)#返回路径名path的规范化绝对路径
os.path.dirname(path)#返回路径path的目录名
os.path.getsize(path)#返回path的大学,以字节为单位
os.path.isabs(path)#如果path为绝对路径,返回Ture
os.path.isdir(path)#如果path是存在的目录返回True
os.path.join(path1[, path2[, ...]])#将多个路径连接起来
os.path.split(path)#将路径path分割成(head,tail)其中tail路径名的最后一部分,head 是其之前的所有部分。
#3.
os.listdir(path)#用于返回指定的文件夹包含的文件或文件夹的名字的列表。
os.path.splitext(path)#将路径名path分割成一个(root, ext)对使得root + ext == path,ext 为空或者以点号开始并至多包含一个点。路径名前面的点号将被忽略;
# 如果目标目录不存在的话,进行目录的新建
import os
if not os.path.exists(target_dir):
    os.makedirs(target_dir)

3.enumerate

  • 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值

  • enumerate多用于在for循环中得到计数

list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
    print index, item
>>>
012 一个
3 测试

4.random模块

import random
1.random.random()
#生成随机0-1小数
2.random.uniform(a,b)
#生成一个指定范围的小数
3.random.randint(a,b)
#生成一个指定范围的整数
4.random.randrange(10,100,2)
#从【10,12,14,16,。。。98】中取出一个随机数
5.random.choice()
#从序列中获取随机元素
random.shuffle()
#将列表中的元素打乱
random.sample()
#从指定的序列中随机获取指定长的片段
list=[1,2,3,4,5,6,7,8,9,10]
s=random.sample(list,5)
print(s)
#[5, 2, 8, 4, 1]

5.文件保存

with open('filename.txt') as file:
   np.save(file,X)  #将X保存为文件的操作
with open(r'filename.txt') as f:
   data_user=pd.read_csv(f)  #文件的读操作
with open('data.txt', 'w') as f:
   f.write('hello world')  #文件的写操作
  

6.数据增强

x=np.flipud(x)
x=np.fliplr(x)
#上下左右翻转

7.np.reshape()

np.reshape(X,(2,3))#将X转成2行3列
np.reshape(X,(-1,3))#将X转成3l
np.reshape(X,(2,-1))

8.函数

np.genfromtxt("{}{}.content".format(path, dataset),dtype=np.dtype(str))#打开文本内容
sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)#创建稀疏矩阵,这里创建全零
idx_features_labels[:, -1]#切片,取最后一列
set(labels)#输出不重复的内容列表

9.保存文件

#1.tensor格式
x = torch.rand(4,5)
torch.save(x, "myTensor.pth")
y = torch.load("myTensor.pth")
print(y)
#2.list格式保存为npy和txt
a = [(u'9000023330249', 1), (u'13142928', 1), (u'9000084906496', 1)]
# 保存
import numpy as np
a=np.array(a)
np.save('a.npy',a) # 保存为.npy格式
# 读取
b=np.load('a.npy')
b=b.tolist()
b
#list->txt
file = open('file_name.txt','w');
file.write(str(list_variable));
file.close();
#numpy array
np.save("filename.npy",a)
b = np.load("filename.npy")
#字典
jsObj = json.dumps(self.dict)  
fileObject = open('dict.json', 'w')  
fileObject.write(jsObj)  
fileObject.close()

10.画图

import matplotlib.pyplot as plt
#导入包

	train_Loss_list.append(loss_train.item())
    train_Accuracy_list.append(acc_train.item())
    val_Loss_list.append(loss_val.item())
    val_Accuracy_list.append(acc_val.item())

x1 = range(0, 500)
x2 = range(0, 500)
x3 = range(0, 500)
x4 = range(0, 500)
y1 = train_Accuracy_list
y2 = train_Loss_list
y3 = val_Accuracy_list
y4 = val_Loss_list
plt.subplot(2, 2, 1)
plt.plot(x1, y1, '-')
plt.xlabel('epoches')
plt.ylabel('train accuracy')
plt.subplot(2, 2, 2)
plt.plot(x2, y2, '-')
plt.xlabel('epoches')
plt.ylabel('train loss')
plt.subplot(2, 2, 3)
plt.plot(x3, y3, '-')
plt.xlabel('epoches')
plt.ylabel('val accuracy')
plt.subplot(2, 2, 4)
plt.plot(x4, y4, '-')
plt.xlabel('epoches')
plt.ylabel('val loss')
plt.savefig('ac_loss.jpg')
plt.show()

11.矩阵切片、数组拼接和分裂

d[行起始:行终止,列起始:列终止:步长,高起始:高终止]
d[:,-1,:]
#第一个:是指d中所有行
#第二个-1指d中最后一列
#第三个:指d中所有高
x = np.array([1,2,3])
y = np.array([4,5,6])
np.concatenate([x,y]) 
array([1, 2, 3, 4, 5, 6])

z = np.array([7,8,9])   # 一次拼接多个数组
np.concatenate([x,y,z])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

# 沿着第一个轴拼接   ! x与grid 第二轴相同
x = np.array([[1,2,3]])
grid = np.concatenate([x,grid])

# 沿着第二个轴拼接 (从0开始索引) y与grid 第一轴相同
y = np.array([[1],[2],[3]])
np.concatenate([y, grid], axis=1)
array([[1, 1, 2, 3],
       [2, 1, 2, 3],
       [3, 4, 5, 6]])

In[48]: x = np.array([1, 2, 3])
grid = np.array([[9, 8, 7],
[6, 5, 4]])
# 垂直栈数组
np.vstack([x, grid])
Out[48]: array([[1, 2, 3],
[9, 8, 7],
[6, 5, 4]])

In[49]: # 水平栈数组
y = np.array([[99],
[99]])
np.hstack([grid, y])
Out[49]: array([[ 9, 8, 7, 99],
[ 6, 5, 4, 99]])
#数组分裂
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [3, 6])   # [3,6]  表示 x数组在 索引3和6进行分裂
x1
array([1, 2, 3])

12.列表、数组、矩阵、numpy、张量Tensor

#1.列表
#list的元素可以是任何对象
a=[]
a=[n for n in range(0,20,2)]
#2.数组array对象可以直接保存数值,但是由于它不支持多维,在上面的函数也不多,因此也不适合做数值运算。
a=np.zeros([2,3])
a=np.ones([2,3])
a=np.array([[2,3,4],[3,4,5]])
#3.矩阵
#数组中的元素可以是字符等
#矩阵中的只能是数
a=np.mat([[2,3],[4,5]])
a=np.eye(3)#三维单位矩阵
#创建对角矩阵
a=np.array([2,3,4])
a=np.diag(a)
#Pytorch里面处理的最基本的操作对象就是Tensor(张量),它表示的其实就是一个多维矩阵,并有矩阵相关的运算操作。在使用上和numpy是对应的,它和numpy唯一的不同就是,pytorch可以在GPU上运行,而numpy不可以。所以,我们也可以使用Tensor来代替numpy的使用。
#ndarray是存储单一数据类型的多维数组
a=np.array([2,3,4,5])
np.array与np.ndarray区别
np.array只是一个便捷的函数,用来创建一个ndarray,它本身不是一个类
你也能够用np.ndarray来创建,但这不是推荐的方式。
#4.张量
#Tensor的基本数据类型有五种:
#32位浮点型:torch.FloatTensor。pyorch.Tensor()默认的就是这种类型。
#64位整型:torch.LongTensor。
#32位整型:torch.IntTensor。
#16位整型:torch.ShortTensor。
#64位浮点型:torch.DoubleTensor。
a = torch.Tensor([[1, 2], [3, 4], [5, 6]])
b=torch.zeros((3,2))
c=torch.randn((3,2))
d=torch.ones((3,2))
#5.相互转换
张量->数组
   ->矩阵
a=torch.Tensor([2,3])
b=np.array(a)
c=np.mat(a)
数组->矩阵
   ->张量
np.mat()
torch.tensor()
矩阵->数组
   ->张量
np.array()
torch.tensor()
列表转数组、矩阵、张量,都需要加上reshape
a=[0,2,4,6,8,10,12,14,16,18]
b=np.mat(a)
b=b.reshape(2,5)
#a3数组或矩阵转换成列表
a4 = a3.tolist()

13.python中的类

class Ticket():
    def __init__(self,checi,fstation,tstation,fdate,ftime,ttime):
        self.checi=checi
        self.fstation=fstation
        self.tstation=tstation
        self.fdate=fdate
        self.ftime=ftime
        self.ttime=ttime
    def printinfo(self):
        print("车次:",self.checi)
        print("出发站:", self.fstation)
        print("到达站:", self.tstation)
        print("出发时间:", self.fdate)

#类中可以定义所使用的方法,类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self;
#init()方法是一种特殊的方法,被称为类的初始化方法,当创建这个类的实例时就会调用该方法;
#self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数;
#创建a1对象
a1=Ticket("G11","xian","beijing",'2019-01-20','13:00','18:00')
#创建a2对象
a2=Ticket("T11","xian","beijing",'2019-01-21','13:00','19:00')
#访问对象属性``
a1.printinfo()
a2.printinfo()

14.numpy库

import numpy as np
1.random

15.随机种子

import random
random.seed ( [x] )
#其中的 x 可以是任意数字,如10,这个时候,先调用它的情况下,使用 random() 生成的随机数将会是同一个。
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ee-redbull

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值