살면서 정말 멋진 강의를 만나는 것은 행운이다.
나는 대학원때 그런 강의를 2번 석사를 마치고 사회에서 개발자로 일하고 있을 때 1번, 이렇게 3번 있었다.
다음 강의 또한 정말 멋지다.
MIT 공개강의 - 선형대수
by Professor Gilbert Strang.
2018년 6월 16일 토요일
[딥러닝] 캡슐네트워크
힌톤교수가 제안하여 더욱 주목을 받았던 신경망이었지만,
미루고 미루다 이제야 살펴보았다.
의미있다.
앞으로 많은 진전이 있을 것 같다.
Dynamic Routing과 Equivariance에 대한 Aurelien Geron의 설명력은 정말 대단하다.
미루고 미루다 이제야 살펴보았다.
의미있다.
앞으로 많은 진전이 있을 것 같다.
Dynamic Routing과 Equivariance에 대한 Aurelien Geron의 설명력은 정말 대단하다.
Capsule Networks from jaypi Ko
2018년 6월 10일 일요일
2018년 5월 23일 수요일
[python] 문법10
--------------------------------------------------------------------------------
#
# 이벤트처리
#
--------------------------------------------------------------------------------
# 화면에 마우스클릭 위치까지 선그리기
import turtle
t = turtle.Turtle()
def drawit(x, y):
#t.penup()
t.goto(x, y)
t.write("click")
s = turtle.Screen()
s.onscreenclick(drawit) #onscreenclick( ) 여기 괄호 안에 들어가는 함수는 변수 2개를 갖도록 되어 있다.
turtle.done()
# 윈도우프로그래밍 = 이벤트처리 프로그래밍
# "스크린 윈도우"에서 "클릭" 이벤트에 대해 클릭위치에 click 출력하는 "처리"를 한 예제
# 터틀에서 하는 방법일 뿐.
# 보다 범용적인 방법 필요: Tk, Qt
--------------------------------------------------------------------------------
# 사건기반(event-driven) 프로그래밍 (~ 윈도우프로그래밍)
# 대표적인 사건: 마우스클릭, 키보드입력 ...
# 사건이 발생되는 토대: 윈도우
[윈도우에서 사건기반 프로그래밍]
- with Turtle in Python
- Win32 API in C
- MFC in C++
- C#, VB
- Java
- Qt in C++
[코딩요소]
- 윈도우생성
- 이벤트처리
- 메세지처리 반복(루프)
[기타]
- 부모윈도우 - 자식윈도우 관계 설정
--------------------------------------------------------------------------------
from tkinter import *
window = Tk()
button = Button(window, text="클릭")
button.pack() # 일단 그냥 하는 걸로
window.mainloop()
----------------------------------------
이벤트 처리 1:
- command; 버튼 클릭할 때 발생; 메뉴 아이템 클릭
----------------------------------------
from tkinter import *
def process():
print("안녕하세요?")
window = Tk()
button = Button(window, text="눌러봐", command=process)
# 버튼에서, command (클릭) 이벤트가 발생하면 process 함수를 호출해라
button.pack()
window.mainloop()
----------------------------------------
윈도우 크기 및 배치
----------------------------------------
from tkinter import *
def process():
print("안녕하세요?")
window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)
button = Button(window, text="클릭", command=process)
btn.place(x=0, y=0, width=100, height=100)
# btn.destroy()
window.mainloop()
# 기타 배치관리자: pack; grid;
# 웹브라우저(부모 윈도우)같이 윈도우의 크기가 (확대/축소)변경되는 경우 pcak, grid가 유용할 수 있음
----------------------------------------
에딧 윈도우
----------------------------------------
from tkinter import *
def onHello():
msg = edt.get()
edt2.insert(10, msg)
window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)
btn = Button(window, text='hello', command=onHello)
btn.place(x=0, y=0, width=100, height=100)
edt = Entry(window, bg='white', fg='black')
edt.place(x=100, y=0, width=200, height=100)
edt2 = Entry(window, bg='white', fg='red')
edt2.place(x=100, y=100, width=200, height=100)
window.mainloop()
[참고자료]
http://effbot.org/tkinterbook/
https://www.tutorialspoint.com/python/tk_button.htm
https://www.python-course.eu/tkinter_layout_management.php
----------------------------------------
이벤트처리2
bind()
: 마우스 움직임 이벤트
printxy(event): event
----------------------------------------
from tkinter import *
def printxy(event):
print(event.x, event.y)
window = Tk()
window.title("my")
window.geometry("500x500")
window.resizable(0, 0)
window.bind("", printxy)
window.mainloop()
[참고자료]
https://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-16-sect-9.html
----------------------------------------
캔바스 - 그림 그리는 함수가 포함되어 있음
create_oval(x1, y1, x2, y2, fill="blue")
----------------------------------------
#
# 오른쪽 버튼 다운 이벤트
# 왼쪽버튼 누른 상태에서 마우스 이동 이벤트
# 마우스 이동 이벤트
#
from tkinter import *
mycolor = "blue"
def paint(event):
x1, y1 = ( event.x-5 ), ( event.y-5 )
x2, y2 = ( event.x+5 ), ( event.y+5 )
canvas.create_oval( x1, y1, x2, y2, fill = mycolor)
def changeColor():
global mycolor
mycolor="red"
def toggleColor(event):
global mycolor
if (mycolor == "red"):
mycolor="blue"
else:
mycolor="red"
window = Tk()
window.bind("", toggleColor)
canvas = Canvas(window)
canvas.pack()
canvas.bind("", paint)
button = Button(window, text="red", command=changeColor)
button.pack()
window.mainloop()
[참고자료]
http://www.python-course.eu/tkinter_layout_management.php
http://zetcode.com/gui/tkinter/layout/
--------------------------------------------------------------------------------
윈도우 생성 함수와 이벤트 처리 함수를 하나로 묶어 보자
--------------------------------------------------------------------------------
'''https://docs.python.org/3.5/library/tk.html'''
from tkinter import *
class MyButton(Button):
def __init__(self, window):
self.button = Button(window, text = "저를 클릭해주세요", command = self.Sum)
self.button.pack()
def Sum(self):
sum = 0
for i in range(1, 11):
sum += i
print("합계 : ", sum)
def main():
window =Tk()
a = MyButton(window)
a.Sum()
window.mainloop()
main()
#
# 부연설명
#
Tk() -> 뭔가를 만든다 ~ 생성
MyButton() -> 뭔가를 만든다 ~ 생성
이렇게 생성된 것들을 통칭해서 부르는 단어가 있으면 좋겠다 -> "객체; Object"
Tk() -> Tk 객체 생성
MyButton() -> MyButton 객체 생성
객체가 생성되면서 자동으로 호출되는 함수가 바로 __init__() 함수이다.
이와 같이 객체를 생성하려면, 미리 객체를 정의해 두어야 한다.
객체를 정의하는 방법은,
class 로 시작해서 위와 같이 몇 가지 규칙을 따라 작성해야 한다.
__init__() 함수가 반드시 있어야 한다.
class 내부에서 정의하는 함수들 사이에서 공동으로 사용하는 변수는 self.를 앞에 붙인다.
class 내부에서 정의하는 함수를 호출할 때도 self.를 앞에 붙인다.
class 내부에서 정의한 함수를 사용하려면 다음과 같은 형식을 취한다.
a.Sum()
미리 작성해 둔 class가 갖고 있는 함수나 변수를 유지하면서, 새롭게 함수나 변수를 추가해서 class를 정의하려면 위와 같이 객체이름 뒤 괄호안에 class이름을 넣는다.
class MyButton(Button)
그렇지 않은 경우, 다음과 같이 생략하면 된다.
class MyButton()
위 코드를 안보고 타이핑 가능해야 한다.
[참고자료]
http://zetcode.com/gui/tkinter/layout/
--------------------------------------------------------------------------------
#
# 이벤트처리
#
--------------------------------------------------------------------------------
# 화면에 마우스클릭 위치까지 선그리기
import turtle
t = turtle.Turtle()
def drawit(x, y):
#t.penup()
t.goto(x, y)
t.write("click")
s = turtle.Screen()
s.onscreenclick(drawit) #onscreenclick( ) 여기 괄호 안에 들어가는 함수는 변수 2개를 갖도록 되어 있다.
turtle.done()
# 윈도우프로그래밍 = 이벤트처리 프로그래밍
# "스크린 윈도우"에서 "클릭" 이벤트에 대해 클릭위치에 click 출력하는 "처리"를 한 예제
# 터틀에서 하는 방법일 뿐.
# 보다 범용적인 방법 필요: Tk, Qt
--------------------------------------------------------------------------------
# 사건기반(event-driven) 프로그래밍 (~ 윈도우프로그래밍)
# 대표적인 사건: 마우스클릭, 키보드입력 ...
# 사건이 발생되는 토대: 윈도우
[윈도우에서 사건기반 프로그래밍]
- with Turtle in Python
- Win32 API in C
- MFC in C++
- C#, VB
- Java
- Qt in C++
[코딩요소]
- 윈도우생성
- 이벤트처리
- 메세지처리 반복(루프)
[기타]
- 부모윈도우 - 자식윈도우 관계 설정
--------------------------------------------------------------------------------
from tkinter import *
window = Tk()
button = Button(window, text="클릭")
button.pack() # 일단 그냥 하는 걸로
window.mainloop()
----------------------------------------
이벤트 처리 1:
- command; 버튼 클릭할 때 발생; 메뉴 아이템 클릭
----------------------------------------
from tkinter import *
def process():
print("안녕하세요?")
window = Tk()
button = Button(window, text="눌러봐", command=process)
# 버튼에서, command (클릭) 이벤트가 발생하면 process 함수를 호출해라
button.pack()
window.mainloop()
----------------------------------------
윈도우 크기 및 배치
----------------------------------------
from tkinter import *
def process():
print("안녕하세요?")
window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)
button = Button(window, text="클릭", command=process)
btn.place(x=0, y=0, width=100, height=100)
# btn.destroy()
window.mainloop()
# 기타 배치관리자: pack; grid;
# 웹브라우저(부모 윈도우)같이 윈도우의 크기가 (확대/축소)변경되는 경우 pcak, grid가 유용할 수 있음
----------------------------------------
에딧 윈도우
----------------------------------------
from tkinter import *
def onHello():
msg = edt.get()
edt2.insert(10, msg)
window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)
btn = Button(window, text='hello', command=onHello)
btn.place(x=0, y=0, width=100, height=100)
edt = Entry(window, bg='white', fg='black')
edt.place(x=100, y=0, width=200, height=100)
edt2 = Entry(window, bg='white', fg='red')
edt2.place(x=100, y=100, width=200, height=100)
window.mainloop()
[참고자료]
http://effbot.org/tkinterbook/
https://www.tutorialspoint.com/python/tk_button.htm
https://www.python-course.eu/tkinter_layout_management.php
----------------------------------------
이벤트처리2
bind()
printxy(event): event
----------------------------------------
from tkinter import *
def printxy(event):
print(event.x, event.y)
window = Tk()
window.title("my")
window.geometry("500x500")
window.resizable(0, 0)
window.bind("
window.mainloop()
[참고자료]
https://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-16-sect-9.html
----------------------------------------
캔바스 - 그림 그리는 함수가 포함되어 있음
create_oval(x1, y1, x2, y2, fill="blue")
----------------------------------------
#
#
#
#
#
from tkinter import *
mycolor = "blue"
def paint(event):
x1, y1 = ( event.x-5 ), ( event.y-5 )
x2, y2 = ( event.x+5 ), ( event.y+5 )
canvas.create_oval( x1, y1, x2, y2, fill = mycolor)
def changeColor():
global mycolor
mycolor="red"
def toggleColor(event):
global mycolor
if (mycolor == "red"):
mycolor="blue"
else:
mycolor="red"
window = Tk()
window.bind("
canvas = Canvas(window)
canvas.pack()
canvas.bind("
button = Button(window, text="red", command=changeColor)
button.pack()
window.mainloop()
[참고자료]
http://www.python-course.eu/tkinter_layout_management.php
http://zetcode.com/gui/tkinter/layout/
--------------------------------------------------------------------------------
윈도우 생성 함수와 이벤트 처리 함수를 하나로 묶어 보자
--------------------------------------------------------------------------------
'''https://docs.python.org/3.5/library/tk.html'''
from tkinter import *
class MyButton(Button):
def __init__(self, window):
self.button = Button(window, text = "저를 클릭해주세요", command = self.Sum)
self.button.pack()
def Sum(self):
sum = 0
for i in range(1, 11):
sum += i
print("합계 : ", sum)
def main():
window =Tk()
a = MyButton(window)
a.Sum()
window.mainloop()
main()
#
# 부연설명
#
Tk() -> 뭔가를 만든다 ~ 생성
MyButton() -> 뭔가를 만든다 ~ 생성
이렇게 생성된 것들을 통칭해서 부르는 단어가 있으면 좋겠다 -> "객체; Object"
Tk() -> Tk 객체 생성
MyButton() -> MyButton 객체 생성
객체가 생성되면서 자동으로 호출되는 함수가 바로 __init__() 함수이다.
이와 같이 객체를 생성하려면, 미리 객체를 정의해 두어야 한다.
객체를 정의하는 방법은,
class 로 시작해서 위와 같이 몇 가지 규칙을 따라 작성해야 한다.
__init__() 함수가 반드시 있어야 한다.
class 내부에서 정의하는 함수들 사이에서 공동으로 사용하는 변수는 self.를 앞에 붙인다.
class 내부에서 정의하는 함수를 호출할 때도 self.를 앞에 붙인다.
class 내부에서 정의한 함수를 사용하려면 다음과 같은 형식을 취한다.
a.Sum()
미리 작성해 둔 class가 갖고 있는 함수나 변수를 유지하면서, 새롭게 함수나 변수를 추가해서 class를 정의하려면 위와 같이 객체이름 뒤 괄호안에 class이름을 넣는다.
class MyButton(Button)
그렇지 않은 경우, 다음과 같이 생략하면 된다.
class MyButton()
위 코드를 안보고 타이핑 가능해야 한다.
[참고자료]
http://zetcode.com/gui/tkinter/layout/
--------------------------------------------------------------------------------
2018년 5월 21일 월요일
[python] 파이계산및그래프그리기
import random
import math
import matplotlib.pyplot as plt
xset = []
yset = []
def generateSamples(size):
xset.clear()
yset.clear()
for i in range(size):
x = random.random()
y = random.random()
xset.append(x)
yset.append(y)
def isInsideCircle(x, y):
r = 0.5
distance = (x - 0.5)*(x - 0.5) + (y - 0.5)*(y - 0.5) - r*r
if (distance >= 0.0):
return False
else:
return True
def estimatePi():
circles = 0
squares = len(xset)
x_circle=[]
y_circle=[]
for i in range(squares):
x = xset[i]
y = yset[i]
if (isInsideCircle(x, y)==True):
circles += 1
x_circle.append(x)
y_circle.append(y)
pi = 4 * circles / squares
plt.scatter(x_circle, y_circle)
plt.show()
return pi
def main():
pi = []
nums=[]
for i in range(10000, 10001, 1):
generateSamples(i)
p = estimatePi()
pi.append(p)
nums.append(i)
print("%1.20f"%p)
plt.plot(nums, pi, 'ro')
plt.axis([0, 10000, 3, 3.3])
plt.show()
main()
import math
import matplotlib.pyplot as plt
xset = []
yset = []
def generateSamples(size):
xset.clear()
yset.clear()
for i in range(size):
x = random.random()
y = random.random()
xset.append(x)
yset.append(y)
def isInsideCircle(x, y):
r = 0.5
distance = (x - 0.5)*(x - 0.5) + (y - 0.5)*(y - 0.5) - r*r
if (distance >= 0.0):
return False
else:
return True
def estimatePi():
circles = 0
squares = len(xset)
x_circle=[]
y_circle=[]
for i in range(squares):
x = xset[i]
y = yset[i]
if (isInsideCircle(x, y)==True):
circles += 1
x_circle.append(x)
y_circle.append(y)
pi = 4 * circles / squares
plt.scatter(x_circle, y_circle)
plt.show()
return pi
def main():
pi = []
nums=[]
for i in range(10000, 10001, 1):
generateSamples(i)
p = estimatePi()
pi.append(p)
nums.append(i)
print("%1.20f"%p)
plt.plot(nums, pi, 'ro')
plt.axis([0, 10000, 3, 3.3])
plt.show()
main()
2018년 5월 15일 화요일
[python] 그래프출력
#
# 선그래프 그리기
#
import matplotlib.pyplot as plt
a=[1,2,3,4,5]
plt.plot(a)
plt.show()
y = [2 * x + 1 for x in range(10)]
plt.plot(y)
plt.show()
#
# 막대그리프 그리기
#
import numpy as np
label = ['seoul', 'pusan', 'daegu', 'incheon', 'kwangju', 'daejeon', 'ulsan']
ndata = np.array([5087, 1639, 1180, 1350, 664, 726, 544])
plt.bar(range(ndata.size), ndata)
plt.xticks(range(ndata.size), label)
plt.show()
[참고자료]
https://wikidocs.net/4767
http://bcho.tistory.com/m/1201
http://freeprog.tistory.com/15
# 선그래프 그리기
#
import matplotlib.pyplot as plt
a=[1,2,3,4,5]
plt.plot(a)
plt.show()
y = [2 * x + 1 for x in range(10)]
plt.plot(y)
plt.show()
#
# 막대그리프 그리기
#
import numpy as np
label = ['seoul', 'pusan', 'daegu', 'incheon', 'kwangju', 'daejeon', 'ulsan']
ndata = np.array([5087, 1639, 1180, 1350, 664, 726, 544])
plt.bar(range(ndata.size), ndata)
plt.xticks(range(ndata.size), label)
plt.show()
https://wikidocs.net/4767
http://bcho.tistory.com/m/1201
http://freeprog.tistory.com/15
2018년 5월 14일 월요일
[python] 문법09
#
# 콘솔파입출력: 리다이렉션 기능
#
a=[1,2,3,4,5,6]
for i in range(len(a)-1):
print(a[i],",",end="")
print(a[len(a)-1])
python a.py > a.txt
python a.py >> a.txt
#
#
#
a=[]
for i in range(3):
b = input()
a.append(b)
print(a)
#다음과 같이 키보드에서 입력
1
2
3
>>>['1', '2', '3']
----- a.txt -----
1
2
3
----------------
python a.py < a.txt
>>>['1', '2', '3']
#
# 파일에 출력
#
#
# 텍스트 파일 - 기본
#
----------------------------------------
file = open("test.txt", "w")
file.write('hello')
file.write("\n")
file.write('world')
file.write("\n")
file.close()
file=open("test.txt", "r")
lines = file.read()
file.close()
print(lines)
#
msg = ["HELLO\n", "WORLD\n", "안녕\n"]
file = open("test.txt", "w", encoding='utf-8')
file.writelines(msg)
file.close()
file = open("test.txt", "r", encoding='utf-8')
line = file.readline()
while line != '':
print(line, end='')
line = file.readline()
file.close()
print()
file = open("test.txt", "r", encoding='utf-8')
lines = file.readlines()
file.close()
line = ''
for line in lines:
print(line, end='')
----------------------------------------
리스트에 있는 값 저장
----------------------------------------
import csv
f=open('a.csv', 'w',newline='')
writer=csv.writer(f, delimiter=',')
writer.writerow([1,2,3])
writer.writerow([4,5,6])
f.close()
----a.csv----
1, 2, 3
4, 5, 6
-------------
import csv
f=open('a.csv', 'r', encoding='utf-8')
reader=csv.reader(f)
for line in reader:
print(line)
f.close()
>> 실행결과
['1', '2', '3']
['4', '5', '6']
----------------------------------------
data=[1,2,3]
with open('a.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(data)
----------------------------------------
import numpy as np
data = np.loadtxt('a.csv', delimiter=',', dtype=np.float32)
print(data)
>> 실행결과
[[1. 2. 3.]
[4. 5. 6.]]
----------------------------------------
f = open('a.csv', 'r')
lines = f.read()
print(lines)
f.close()
>> 실행결과
1,2,3
4,5,6
----------------------------------------
#
# 이진파일
#
import pickle
colors = [1, 2, 3, 4]
pickle.dump(colors, open('colors.txt', 'wb'))
mycolors = pickle.load(open('colors.txt', 'rb'))
print(mycolors)
----------------------------------------
# 콘솔파입출력: 리다이렉션 기능
#
a=[1,2,3,4,5,6]
for i in range(len(a)-1):
print(a[i],",",end="")
print(a[len(a)-1])
python a.py > a.txt
python a.py >> a.txt
#
#
#
a=[]
for i in range(3):
b = input()
a.append(b)
print(a)
#다음과 같이 키보드에서 입력
1
2
3
>>>['1', '2', '3']
----- a.txt -----
1
2
3
----------------
python a.py < a.txt
>>>['1', '2', '3']
#
# 파일에 출력
#
#
# 텍스트 파일 - 기본
#
----------------------------------------
file = open("test.txt", "w")
file.write('hello')
file.write("\n")
file.write('world')
file.write("\n")
file.close()
file=open("test.txt", "r")
lines = file.read()
file.close()
print(lines)
#
msg = ["HELLO\n", "WORLD\n", "안녕\n"]
file = open("test.txt", "w", encoding='utf-8')
file.writelines(msg)
file.close()
file = open("test.txt", "r", encoding='utf-8')
line = file.readline()
while line != '':
print(line, end='')
line = file.readline()
file.close()
print()
file = open("test.txt", "r", encoding='utf-8')
lines = file.readlines()
file.close()
line = ''
for line in lines:
print(line, end='')
----------------------------------------
리스트에 있는 값 저장
----------------------------------------
import csv
f=open('a.csv', 'w',newline='')
writer=csv.writer(f, delimiter=',')
writer.writerow([1,2,3])
writer.writerow([4,5,6])
f.close()
----a.csv----
1, 2, 3
4, 5, 6
-------------
import csv
f=open('a.csv', 'r', encoding='utf-8')
reader=csv.reader(f)
for line in reader:
print(line)
f.close()
>> 실행결과
['1', '2', '3']
['4', '5', '6']
----------------------------------------
data=[1,2,3]
with open('a.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(data)
----------------------------------------
import numpy as np
data = np.loadtxt('a.csv', delimiter=',', dtype=np.float32)
print(data)
>> 실행결과
[[1. 2. 3.]
[4. 5. 6.]]
----------------------------------------
f = open('a.csv', 'r')
lines = f.read()
print(lines)
f.close()
>> 실행결과
1,2,3
4,5,6
----------------------------------------
#
# 이진파일
#
import pickle
colors = [1, 2, 3, 4]
pickle.dump(colors, open('colors.txt', 'wb'))
mycolors = pickle.load(open('colors.txt', 'rb'))
print(mycolors)
----------------------------------------
#
# 원그리기 / 파이 추정(근사)하기
#
#
# 무식한 방법으로 근사하기 ~ 몬테카를로 방법
#
import random
import math
import csv
xset = []
yset = []
def generateSamples(size):
xset.clear()
yset.clear()
for i in range(size):
x = random.random()
y = random.random()
xset.append(x)
yset.append(y)
def isInsideCircle(x, y):
r = 0.5
distance = (x - 0.5)*(x - 0.5) + (y - 0.5)*(y - 0.5) - r*r
if (distance >= 0.0):
return False
else:
return True
def estimagePi():
area_square = 10000
area_circle = 0
generateSamples(area_square)
dataset=[0, 0]
with open('a.csv', 'w', newline='') as csvfile:
points = csv.writer(csvfile, delimiter=',')
for i in range(len(xset)):
x= xset[i]
y = yset[i]
if (isInsideCircle(x, y)==True):
dataset[0]=x
dataset[1]=y
'''points.writerow(dataset)'''
area_circle = area_circle + 1
return 4.0 * area_circle / area_square
pi = estimatePi()
print("pi = %10.9f"%(pi))
----------------------------------------------------------------------------------------
피드 구독하기:
글 (Atom)
