
Python
Python笔记
JuyongJiang
Follow your own pace. To be the best.
展开
-
Python基础总结笔记
0 环境搭建Unix & Linux# tar -zxvf Python-3.6.1.tgz# cd Python-3.6.1# ./configure# make && make install1 特点1、可扩展:如果需要一段运行很快的关键代码,或者是想要编写一些不愿开放的算法,可以使用C或C++完成那部分程序,然后从Python程序中调用。2、数据库:...原创 2020-02-23 03:47:01 · 981 阅读 · 0 评论 -
利用Python的random模块获取任意范围随机数
随机函数import randomrandom.random() #0到1的随机浮点数 [0, 1)random.uniform(a, b) #生成指定范围内的随机浮点数[a, b]random.randint(a, b) #生成指定范围内的整形数[a, b]random.randrange([a], b[, step]) #[a, b), step 按照指定的步长,随机从指定范围选取整形值 等效于 == random.choice(range(a, b, step))#sequence可原创 2021-01-25 10:10:58 · 2338 阅读 · 1 评论 -
pytorch模型的保存、加载和微改
保存pytorch模型的两种方法import torch'''保存pytorch模型的两种方法'''## 保存整个神经网络的结构信息和模型的参数信息,save的对象是网络nettorch.save(model_object, 'net.pth')model = torch.load('net.pth')## 只保存神经网络的训练模型参数,save的对象是net.state_dict()torch.save(model_object.state_dict(), 'net.pth')mod转载 2021-01-19 18:14:00 · 926 阅读 · 0 评论 -
利用opencv-python实现视频转图片, 和图片转视频互转
关键点:视频–>图片cap = cv2.VideoCapture(video_path)success, frame = cap.read()图片–>视频video = cv2.VideoWriter(videoPath, fourcc, fps, size)video.write(img)完整代码import cv2import osimport shutildef video2imgs(videoPath, imgPath, interval=1): if n原创 2021-01-19 17:07:22 · 447 阅读 · 0 评论 -
pytorch加载模型时出现.....xxx.pth is a zip archive (did you mean to use torch.jit.load()?)
Bug原因: 训练和测试的torch版本不一致。训练的时候是1.x,测试的时候是1.m。解决办法: 先在1.x版本下加载模型,然后在保存的时候设置use_new_zipfile_serialization=False 就行了。#torch_version==1.ximport torchfrom models import netcheckpoint = 'xxx.pth'model = net()model.load_state_dict(torch.load(checkpoint))m原创 2021-01-19 16:05:56 · 7894 阅读 · 1 评论 -
使用python内置函数dir() getattr() setattr()编写模型Config配置文件
内置函数简介dir()函数:列出模块定义的标识符(函数,类或者变量)getattr(object, name, default):取得object的name成员的value。如果name成员不存在就返回default的value;如果default未给出则raise AttributeError.setattr(object, name, value):新建/修改object的name成员的值为value。配置文件Configconfig.py#directory to save weight原创 2021-01-19 12:38:39 · 573 阅读 · 0 评论 -
Pytorch: split() 函数
作用:对tensor在某一dim维度下,根据指定的大小split_size=int,或者list(int)来分割数据,返回tuple元组。torch.split(tensor, split_size_or_sections, dim=0)注意两个细节:1、当split_size为一个int数时,若不能整除int,剩余的数据直接作为一块。2、当split_size为一个列表时,所有数字的和等于要分割的维度大小。#细节1import torchinput = torch.randn(4,10,8)原创 2020-08-06 03:11:54 · 17065 阅读 · 0 评论 -
Pytorch模型中同时定义多个可训练的单变量
定义多个可训练的尺度权重系数import torchfrom torch import nnclass Scale(nn.Module): def __init__(self, init_value=1.0): super(Scale, self).__init__() self.scale = nn.Parameter(torch.FloatTensor([init_value])) def forward(self, input):原创 2020-08-05 19:58:01 · 2711 阅读 · 2 评论 -
OSError: Could not find kaggle.json. Make sure it‘s located in /home/user/.kaggle.
Bug: OSError: Could not find kaggle.json. Make sure it’s located in /home/jyjiang/.kaggle. Or use the environment method.原因:当利用kaggle上传和下载文件时,kaggle需要知道账号的身份信息。解决:kaggle --> My Account --> API --> Create New API Token,下载得到kaggle.json文件,放在/home/u原创 2020-08-04 22:31:08 · 6838 阅读 · 4 评论 -
Pytorch函数使用记录
文章目录F.conv2d (函数式接口)torch.nonzerotorch.wheretorch.clamptorch.linspacetorch.repeattorch.topk|torch.sort|torch.ne|torch.min|torch.max|torch.lt|torch.le|torch.kthvalue|torch.gt|torch.ge|torch.equal|torch.eqF.conv2d (函数式接口)Pytorch里一般小写的都是函数式的接口,相应的大写的是类式接口,函原创 2020-08-04 00:57:29 · 553 阅读 · 0 评论 -
Pytorch:gather函数
TORCH.GATHER作用:从张量中根据下标位置沿指定dim取出指定元素聚合成新张量#函数定义torch.gather(input, dim, index, out=None, sparse_grad=False) → Tensor注意蓝绿色框内的下标,也就可以明白该函数的使用。由红框中的内容可知,out的大小和index的大小是一样的。index需要和input具有除了dim以外相同的维度数。Example:#一维t = torch.tensor([1, 3, 5, 0, 9])原创 2020-08-03 13:31:33 · 324 阅读 · 0 评论 -
读取.json文件绘制模型训练acc和loss变化曲线
模型训练过程保存在.json文件中,读取.json绘制acc和loss变化曲线,方便观察模型随Iteration收敛情况的变化:代码实现:1、两个模型训练acc随Iteration的变化import matplotlib.pyplot as pltfrom matplotlib.pyplot import MultipleLocatorimport jsondata_path_1 = "./1.json"data_path_2 = "./2.json"def read_json(data_原创 2020-07-30 01:56:06 · 2484 阅读 · 1 评论 -
远程访问Linux服务器的JupyterLab
目录1、登录远程Linux服务器2、安装JupyterLab3、生成配置文件4、设置密码5、修改配置文件6、安装Node.js7、启动JupyterLab8、远程访问指定的端口,服务器对外开放指定的端口,服务器不对外开放本文的配置方法对于Jupyter Notebook一样有效1、登录远程Linux服务器2、安装JupyterLabpip install jupyterlab3、生成配置文件jupyter notebook --generate-config#生成的文件位于:~/.jupyt原创 2020-07-22 02:57:13 · 1822 阅读 · 0 评论 -
Pytorch:expand_as() 和 expand()用法
expand的含义:为1的维度可以变大维度或者维度数增多tensor_1.expand(size):把tensor_1扩展成size的形状tensor_1.expand_as(tensor_2) :把tensor_1扩展成和tensor_2一样的形状import torch#1x = torch.randn(2, 1, 1)#为1可以扩展为3和4x = x.expand(2, 3, 4)print('x :', x.size())>>> x : torch.Size([2原创 2020-07-01 02:35:07 · 14263 阅读 · 1 评论 -
Python: Excel数据的读写操作
模块的安装利用Python处理excel格式数据文件需要安装xlrd模块pip install xlrdpip install xlsxwriter数据的读取import xlrd#打开excle数据文件xl = xlrd.open_workbook(r'./data.xlsx')#通过索引获取工作表table = xl.sheets()[0]print(table) # 获取行数rows = table.nrowsprint(rows)cols = table.ncols原创 2020-06-23 23:31:33 · 266 阅读 · 0 评论 -
Pytorch: 插值和上采样
nn.Upsample定义import torch.nn as nnimport torch.nn.functional as Fnn.Upsample(size=None, scale_factor=None, mode='nearest', align_corners=None)F.upsample(input, size=None, scale_factor=None, mode='nearest', align_corners=None)参数align_corners上图是s原创 2020-06-06 20:55:18 · 2059 阅读 · 0 评论 -
Pytorch: Pooling layers详解
目录MaxPoolAdaptiveMaxPoolAvgPoolAdaptiveAvgPoolPooling layers属于torch.nn包下https://pytorch.org/docs/stable/nn.html#pooling-layersNOTE: 1d和2d和3d使用的方式都是相同的;本质的区别就在于操作的对象是多少维度的,1d是对一维的向量进行操作,2d是对二维的矩阵进行操作,3d是对三维的矩阵进行操作。import torch.nn as nnMaxPool定义nn.原创 2020-06-06 20:16:17 · 4749 阅读 · 1 评论 -
Python: print数组/矩阵/张量完整输出
问题:当数组/矩阵过大则只会显示其中一部分,中间会自动用省略号代替:import numpy as npmatrix = np.zeros((100,100), dtype = np.int) print(matrix)解决:通过set_printoptions()设定显示全部import numpy as npnp.set_printoptions(threshold=np.inf)matrix = np.zeros((100,100), dtype = np.int) print(原创 2020-06-04 11:10:53 · 10851 阅读 · 3 评论 -
Python: OS模块文件/目录方法
os 模块提供了非常丰富的方法用来处理文件和目录,常用的方法如下:os.pathos.path.abspath(path) #返回绝对路径os.path.isabs(path) #判断是否为绝对路径os.path.isdir(path) #判断路径是否为目录os.path.isfile(path) #判断路径是否为文件====================================================os.path.realpath(path) #返回path的真实路径原创 2020-06-04 10:52:28 · 270 阅读 · 0 评论 -
numpy.where()用法详解
numpy.where()有两种用法1、np.where(condition, x, y)满足条件(condition),输出x,不满足输出y#1>>> aa = np.arange(10)>>> np.where(aa,1,-1)array([-1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) # 0为False,所以第一个输出-1#2>>> np.where(aa > 5,1,-1)array(转载 2020-05-31 02:35:10 · 1406 阅读 · 1 评论 -
使用 IMDB review 数据集用于文本分类
IMDB review 数据集介绍JSON文件读写操作详解imdb_review.json[ { "rating": 5, "title": "The dark is rising!", "movie": "tt0484562", "review": "It is adapted from the book. I...原创 2020-04-01 12:42:03 · 1665 阅读 · 0 评论 -
JSON文件读写操作详解
JSON介绍JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。[百度百科]JS...原创 2020-03-31 19:46:38 · 21376 阅读 · 0 评论 -
Python的10个高效的编程Tricks
True, practice alone is not perfect, but perfect practice is. This means that you need to make sure that you are always following the best coding practices (commenting on your code, using correct syn...原创 2020-03-30 21:58:35 · 336 阅读 · 0 评论 -
PyTorch : nn.Linear() 详解
线性转换:举例:input1 = torch.randn(128, 20)input2 = torch.randn(128, 3, 20) #中间 * 可以添加任意维度input3 = torch.randn(128, 3, 4, 20) m = nn.Linear(20, 30)output1 = m(input1)output2 = m(input2)output3 = m(...原创 2020-03-28 02:28:28 · 6001 阅读 · 0 评论 -
torch.mul | torch.mm | torch.bmm | torch.matmul的区别和使用
torch.mul用法torch.mul(input1, input2, out=None)功能1、两个对位相乘,可以广播举例torch.mmtorch.bmmtorch.matmul原创 2020-03-28 01:19:26 · 2517 阅读 · 0 评论 -
ERROR:ModuleNotFoundError: No module named 'sklearn'
Bug : ERROR:ModuleNotFoundError: No module named ‘sklearn’解决:安装scikit-learnconda install scikit-learnorpip install scikit-learn原创 2020-03-27 05:01:10 · 228 阅读 · 0 评论 -
Python : 字典按键和值排序
[1] sorted()函数排序函数 sorted(iterable,key,reverse),iterable表示可迭代的对象,例如可以是dict.items()、dict.keys()等;key是一个函数,用来选取参与比较的元素;reverse则是用来指定排序是倒序还是顺序,reverse=true则是倒序,reverse=false时则是顺序(默认)。[2] 按key排序1、sorte...原创 2020-03-05 21:08:09 · 284 阅读 · 0 评论 -
81. Search in Rotated Sorted Array II
#加入了重复元素,会导致,无法准确的判定 mid 元素到底位于左、右哪个区域,简单的方法就是不改变顺序的去重,原来的方法即可生效Search in Rotated Sorted Arrayclass Solution: def search(self, nums: List[int], target: int) -> int: nums = list(set(n...原创 2020-03-04 21:13:57 · 115 阅读 · 0 评论 -
33. Search in Rotated Sorted Array
class Solution: def search(self, nums: List[int], target: int) -> int: low = 0 high = len(nums)-1 while low <= high: mid = (low+high) // 2 i...原创 2020-03-04 19:56:22 · 108 阅读 · 0 评论 -
20. Valid Parentheses
#利用字典存放匹配规则class Solution: def isValid(self, s: str) -> bool: if s == "": return True if len(s) == 1: #只有一个字符时 return False stack = [] ...原创 2020-03-04 18:13:56 · 104 阅读 · 0 评论 -
84. Largest Rectangle in Histogram
#关键就是找到一个元素左、右边第一个比它小的元素,然后计算 宽度 × 自身高度class Solution: def largestRectangleArea(self, heights: List[int]) -> int: ans = 0 stack = [] heights = [0] + heights + [0] #便于...原创 2020-03-04 17:23:27 · 95 阅读 · 0 评论 -
61. Rotate List
#翻转k次 等效于 从count-k那个结点开始循环遍历一遍,在k % count ==0 时,序列不变# Definition for singly-linked list.class ListNode: def __init__(self, x): self.val = x self.next = None class Solution...原创 2020-03-03 03:35:10 · 127 阅读 · 0 评论 -
74. Search a 2D Matrix
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: #二分查找在矩阵中的应用 if matrix == [] or matrix == [[]]: return False row = le...原创 2020-03-02 20:32:51 · 118 阅读 · 0 评论 -
58. Length of Last Word
class Solution: def lengthOfLastWord(self, s: str) -> int: temp=s.split(" ") for word in temp[-1::-1]: if word != "": return len(word) retu...原创 2020-03-02 18:44:48 · 107 阅读 · 0 评论 -
905. Sort Array By Parity
#利用快速排序的思想,序列两边同时进行比较,时间复杂度为:O(n)class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: i = 0 j = len(A)-1 L_num = A[j] #取出最后一个值 while i < ...原创 2020-03-02 13:01:15 · 232 阅读 · 0 评论 -
50. Pow(x, n)
import mathclass Solution: def myPow(self, x: float, n: int) -> float: return math.pow(x,n)class Solution: def myPow(self, x: float, n: int) -> float: res = 1 ...原创 2020-02-29 05:33:17 · 155 阅读 · 0 评论 -
32. Longest Valid Parentheses
class Solution: def longestValidParentheses(self, s: str) -> int: stack = [0] ret = 0 for char in s: if (char == "("): stack.append(0) ...原创 2020-02-29 04:52:55 · 115 阅读 · 0 评论 -
Anaconda使用总结
目录1、Anaconda简介2、Anaconda安装(Linux和Windows)3、Conda的包管理与环境管理1、Anaconda简介Anaconda是一个用于科学计算的Python发行版,支持 Linux、 Mac、Windows系统,提供了包管理与环境管理的功能,可以很方便地解决多版本python并存、切换以及各种第三方包安装问题。Anaconda利用工具/命令conda来进行p...原创 2020-02-13 07:40:07 · 4863 阅读 · 0 评论 -
1. Two Sum
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)-1): comp=target-nums[i] for j in range(i+1,len(nums)): ...原创 2020-02-23 00:48:46 · 125 阅读 · 0 评论 -
2. Add Two Numbers
# Definition for singly-linked list.class ListNode: def __init__(self, x): self.val = x self.next = None#Use listnode to get a decimal numberclass GetNum: snode = None ...原创 2020-02-25 08:06:26 · 145 阅读 · 0 评论