"""
attribute = 속성. class의 맴버함수 but ()이 필요 없음
<tensor class>
1. .requires_grad : 이 attribute를 True 로 설정하면, 그 tensor에서 이뤄진 모든 연산들을 추적(track)하기 시작
2. .backward() : 호출하여 모든 변화도(gradient)를 자동으로 계산
3. .grad 속성: 이 Tensor의 변화도가 누적됨.
4. .detach() : Tensor가 기록을 추적하는 것을 중단하게 하려면
5. with torch.no_grad(): gradient는 필요없고, 메모리는 절약하고 싶고, 학습가능한 매개변수로 찾고 싶을때.
<Function class>
부호화(encode)하여 순환하지 않는 그래프(acyclic graph)를 생성
1. .grad_fn : Tensor 를 생성한 Function 을 참조
"""pass
x=torch.ones(2,2,requires_grad=True)y=x+4print(y)# AddBackward0 : track all operations
print(y.grad_fn)# 사용자가 마지막으로 이 변수를 만들 때 사용하는 Function을 참조한다. (기억해 놓는다.)
tensor([[5., 5.],
[5., 5.]], grad_fn=<AddBackward0>)
<AddBackward0 object at 0x000001B1F842D2C8>
# tensor에서 * / 는 행렬의 곱이 아니라, 같은 위치 원소의 연산이다.
k=torch.tensor([[1,2],[3,4]],requires_grad=True,dtype=torch.double)print(k*k)
x1=torch.ones(2,2,requires_grad=True)x2=x1+3x3=3*(x2**2)out=torch.mean(x3)# 1/4 처리가 된다. 4개 원소 평균이므로
# ()에 아무것도 넣지 않으면, torch.tensor(1.). 이 값이 Backpropa의 가장 첫번째 upstream gradient이다.
# 그래서 out이 스칼라여야 하는 것이다. mean을 안하고 x3 = out으로 하고 backward하면, 계산 불가.
out.backward()# d_out/d_x1 = 3*2/4 ... = 3/2(x+3)|x = 1 = [[6,6],[6,6]]
print(x1.grad)# x1.grad는 # d_<backward한것> / d_<.grad 한것> 의 값이 나온다.
# 생각해보면 d_Loss/d_x1를 이용해 x1을 갱신해야하므로, x1과 똑같은 size의 tensor가 print된다
''' 위에꺼 주석하고 이것도 해보기.
x3.backward(torch.tensor([[1,1],[1,1]],dtype=torch.double)) # d_out/d_x1 = 3*2/4 ... = 3/2(x+3)|x = 1 = [[6,6],[6,6]]
print(x1.grad) # 생각해보면 d_Loss/d_x1를 이용해 x1을 갱신해야하므로, x1과 똑같은 size의 tensor가 print된다
'''pass
tensor([[6., 6.],
[6., 6.]])
# 이 with 내부에 작성한 모든 연산들은 gradient tracking을 하지 않는다.
withtorch.no_grad():print((x1**2).requires_grad)
False
# .detach() 를 호출하여 내용물(content)은 같지만 require_grad가 다른 새로운 Tensor를 가져옵니다
print(x3.requires_grad)y3=x3.detach()print(y3.requires_grad)print(x3.eq(y3).all())# https://pytorch.org/docs/stable/tensors.html#torch.BoolTensor
원본 글 위치 : https://junha1125.tistory.com/53?category=836123
**
1. Git : MSTAR-tensorflow (star : 28)
Git 사이트에 의하면, [https://github.com/hamza-latif/MSTAR_tensorflow] 다음과 같은 Instruction이 있었다.
We want to train a deep neural network to identify targets in the three class MSTAR dataset obtained from \1. [https://www.sdms.afrl.af.mil/index.php?collection=mstar&page=targets] and possibly the ten class dataset from \2. [https://www.sdms.afrl.af.mil/index.php?collection=mstar&page=mixed]
이 사이트를 참고하여, Mstar에서 재공하는 public data를 찾아보았다.
Original Website -> [https://www.sdms.afrl.af.mil/index.php] 이 사이트에 회원가입하고(국민대 계정 메일 확인) Download링크를 찾아가면, 그림2의 사이트로 들어갔다. (위 인용구 2개의 사이트 둘 다 그림2로 갔다.)
그림2
그리고 targets와 mixed와 가장 관련이 깊은 다음의 파일을 다운받아 보았다.
1-1 ReadMe 정리
- Abstract
SAR (Synthetic Aperture Radar) 객체 인식은 군사 응용 분야에서 자동 표적 인식 및 공중 정찰에 중요한 문제입니다. SAR 이미지에서 유용한 Feature를 extract하고, classification하기 위해 deep CNN을 사용할 것이다. 데이터 셋은 공개적으로 사용 가능한 MSTAR(Moving and Stationary Target Acquisition and Recognition)을 사용할 것이다.
# print function에 대하여, 2.x 3.x 버전 둘다 사용가능하게 해줌. print x,y; print(x,y)
from__future__importprint_function
# 메모리 할당만 해주고, 값은 정의 하지 않는다. 쓰레기 값 저장되어 있을 것.
x=torch.empty(5,3)print(x)# 배열을 생성하고 싶을 때. 아래의 값들은 모두 tensor([[],[]])로 저장되어 있다.
y=torch.rand(2,3)z=torch.zeros(2,3)k=torch.ones(2,3,dtype=torch.double)# torch.double == torch.float64
j=torch.rand_like(k,dtype=torch.float)# k와 동일한(like) 크기를 가지는 rand tensor를 만든다
# object.size() == object.shape. torch.size는 사실 튜플이다. 모든 곳에서 튜플처럼 이용할 수 있다.
print(j.shape,' ==? ',j.size())n=torch.rand(j.shape)m=torch.rand(j.size())print(type(j.size()))# list를 가지고 있다면 직접 tensor생성
i=torch.tensor([1,2,3,4])
# operator 같은 size 텐서에서 + - 연산 가능
q=y+zq=torch.add(y,z)q=torch.empty(9,8)#; print(q)
torch.add(y,z,out=q)#; print(q) # torch.add 함수는 자동으로 print해준다.
y.add(z)# ; y += z
# 바꿔치기 연산자. 어떤 변수를 통체로 바꿔버리고 싶다면 _ 를 사용하는 메소드를 사용하라.
k.copy_(z)# 아무리 그래도 y와 z의 shape는 같아야 한다.
y.t_()# 슬라이싱도 사용할 수 있다. numpy와 같은 방식이다.
print(y[:,1].type(torch.int))print(y[:,1].to(torch.int))
# tensor와 numpy의 관계는 copy of referecne 관계이다.
a=torch.tensor([1,1,1,2,2])b=a.numpy()print(b)a.add_(1)print(b,"\n -----")# numpy를 tensor로 변환
importnumpyasnpa=np.ones([2,3])b=torch.from_numpy(a)np.add(a,1,out=a)print(a,"\n",b)
# cuda 사용하기. to 메소드를 사용하면 된다.
iftorch.cuda.is_available():device=torch.device("cuda")#cuda사용할 수 있는 gpu id를 device라는 것
y=torch.ones_like(x,device=device)#변수 선언을 할 때 처음부터 device를 지정해도 되고,
x=x.to(device)#나중에 to메소드를 사용해서 device를 지정해도 된다.
z.to("cpu",torch.double)
echo print 해준다. echo $HOME : HOME이라고 이름 지어진 환경변수의 path를 print해준다. echo $PATH : 여기에 있는 프로세스 파일은 무조건 실행 가능 echo “ttt” » : 파일내부에 이 문자열을 추가해준다. echo "tt" > <임의의 파일=""> : 원래 있던 내용 다 지우고, 지금 문자열만 추가해준다.임의의>
cat : 내부 내용을 뿌려준다.(파일 내용을 본다) cat ./.bashrc
touch 파일을 만들어 준다.
which
cd - == cd ..
rmdir
rm -rf
cp : copy
mv : mv, rename
find . -name : .은 pwd아래의 모든 폴더를 뒤져본다.
df dist 정보를 보여준다. df -m : 메가 바이트 단위로 알려준다.
du -sm /home 해당 부위에 사용하고 있는 용량 검색. 메가 바이트 단위
free -m 메모리 사용량 검색
top space bar를 이용해서 갱신해 준다. 1을 누루면 cpu의 core에 관한 정보가 보여진다
vmstat 좀 더 간단하게 하드웨어 사용량 vmstat 1 : 1초 단위 그려준다
grep 단어 뽑아 내기 ps -ef | grep bash bash가 들어간 내용만 뽑아준다.
sh tt.sh touch tt.sh echo ‘#!/bin/sh’ » tt.sh echo ‘ls’ > tt.sh sh tt.sh와 같이 sh내부의 명령어 실행 sh말고 bash라고 처도 된다.
chmod 나(root) /그룹(group) /다른사람들(users) rwe : 읽기 쓰기 실행 111 111 111 -> 7 7 7 chmod 777 .sh파일은 권한이 허락된다면 $ tt.sh만으로 실행이 가능하다.
chown 파일의 소유자를 바꿔준다. chown :<groupName(group이 없으면 user 이름 그대로)>
ln ln -s : symbolic link 달기 : 바로가기 만들기 ln -s <목적지> <바로가기 파일이름="">바로가기>목적지>
export 터미널에 새로운 변수를 만들어 준다.
env export했던 것등 모든 변수들을 보여준다.
grep ctrl + f 같은 느낌이다. 다양한 옵션과 표현식을 넣어줌으로써 다양한 방식으로 내가 원하는 문자의 위치를 찾을 수 있다. (grep 명령어 사용법 구글검색해보기)
ubuntu variable setting
$ A="/user/home/workspace"# Shell에 새로운 변수 Define$ A=/user/home/workspace
$ echo${A}$ echo$A
defsolution(words):words.sort()# make zero vector
counter_vector=[]foriinrange(len(words)):counter_vector.append([0forjinrange(len(words[i])+1)])# fill counter_vector
word_stack=['0']*MAX_COUNTforiinrange(len(words)):fill_current_vector(i,words,counter_vector,word_stack)#print(counter_vector)
# return answer
answer=0foriinrange(len(words)):answer+=sum(counter_vector[i])returnanswerMAX_COUNT=1000deffill_current_vector(current_word,words,counter_vector,word_stack):while(1):current_step=counter_vector[current_word].index(0)word_stack[current_step]=words[current_word][current_step]foriinrange(current_word,len(words)):ifcurrent_step>len(words[i])-1:breakifword_stack[current_step]==words[i][current_step]andcounter_vector[i].index(0)==current_step:counter_vector[i][current_step]=1else:break# break condition 1
ifcounter_vector[current_word][-2]==1:break# break condition 2, 3
ifcurrent_word==len(words)-1:breakelse:ifcounter_vector[current_word+1][current_step]==1:passelse:break
2. Trie
Trie구조를 사용하기 위한 python 기본 지식cur = dict()ccur = {}cur[‘c’] = ‘value’ cur[‘c’] = {‘num’ :1}print(cur) » {‘c’: {‘num’: 1}}
a.
defsolution(words):char_freq={}forwordinwords:cur=char_freqforcharinword:try:cur[char]['num']+=1except:cur[char]={'num':1}cur=cur[char]# cursor 를 마지막에 갱신
res=0forwordinwords:cur=char_freqforcharinword:res+=1ifcur[char]['num']==1:breakelse:cur=cur[char]returnres