Python2023. 6. 1. 17:34

chatGPT 에게 LSTM 간단한 예제를 만들어 달라고 했더니 이런걸 만들어 준다.

LSTM(Long Short-Term Memory)은 순환 신경망(RNN)의 한 종류로서, 장기 의존성(long-term dependency)을 학습하기에 효과적인 구조를 가진 모델입니다. LSTM은 시계열 데이터나 자연어 처리와 같이 순차적인 데이터를 다루는데 주로 사용됩니다. by ChatGPT

 

import numpy as np
import tensorflow as tf

# 입력 시계열 데이터 생성
# 간단한 사인 함수를 사용하여 시계열 데이터를 생성합니다.
def generate_sequence(length):
    freq = np.random.uniform(0.1, 1.0)
    x = np.sin(np.arange(0, length) * freq)
    return x

# 데이터셋 생성
def generate_dataset(seq_length, n_samples):
    X = []
    Y = []
    for _ in range(n_samples):
        seq = generate_sequence(seq_length)
        X.append(seq[:-1])  # 입력 시퀀스
        Y.append(seq[1:])   # 출력 시퀀스
    X = np.array(X)
    X = np.reshape(X, [n_samples, seq_length-1, 1])
    Y = np.array(Y)
    Y = np.reshape(Y, [n_samples, seq_length-1, 1])
    return X, Y

# LSTM 모델 생성
def create_lstm_model(seq_length):
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.LSTM(20, input_shape=(seq_length-1, 1), return_sequences=True))
    model.add(tf.keras.layers.Dense(1, activation='linear'))
    return model

# 데이터셋 생성
seq_length = 10
n_samples = 1000
X, Y = generate_dataset(seq_length, n_samples)

# LSTM 모델 생성
model = create_lstm_model(seq_length)

# 모델 컴파일
model.compile(loss='mse', optimizer='adam')

# 모델 훈련
model.fit(X, Y, epochs=10, batch_size=32)

# 새로운 시퀀스 생성 및 예측
new_seq = generate_sequence(seq_length)
new_input = new_seq[:-1]
new_input = np.reshape(new_input, [1, seq_length-1, 1])
predicted_output = model.predict(new_input)
print("입력 시퀀스:", new_seq[:-1])
print("예측된 다음 값:", predicted_output.flatten())

 

만들어진 코드를 코랩(colab)에서 실행

잘 된다.

Posted by 비니미니파
Python2023. 5. 19. 15:11

python schedule 을 이용한 프로그램 시작과 종료

import schedule
import time

current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# print(current_time)

def start_program():
    print(current_time)
    print("프로그램이 시작되었습니다.")

def end_program():
    print(current_time)
    print("프로그램이 종료되었습니다.")

# 시작 시간과 종료 시간 설정
start_time = "15:05"  # 시작시간
end_time = "15:06"  # 종료시간

# 스케줄링된 작업 추가
schedule.every().day.at(start_time).do(start_program)  # 시작 시간에 프로그램 시작 작업 추가
schedule.every().day.at(end_time).do(end_program)  # 종료 시간에 프로그램 종료 작업 추가

# 무한루프를 돌며 스케줄링된 작업 실행
while True:
    schedule.run_pending()
    time.sleep(1)

 

내가 안짰음...

chatgpt 가 짜줌 ^^

 

Posted by 비니미니파
Python2023. 4. 4. 14:47

 

import time

from datetime import datetime

while True:

    # 현재 시간 출력 YYYY-MM-DD HH:MI:SS 
    s = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    print(s)

    # 1초간 sleep
    time.sleep(1)

 

python 시간 포맷을 알아보려면 아래 사이트를 방문 하자!

https://docs.python.org/3/library/datetime.html

 

datetime — Basic date and time types

Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attr...

docs.python.org

 

Posted by 비니미니파
Python2021. 11. 10. 10:52

1에서 10까지 값 만들기

import numpy as np

# 1~10까지 만들기
a = np.arange(1,11)

print(a)

결과 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

만들어진 1~10까지 더하기 : 누적합(Cumulative Sum) : np.cumsum

# 1~10까지 더하기
b = np.cumsum(a)

print(b)

결과 : [ 1 3 6 10 15 21 28 36 45 55]

* 수학 공식

( 첫번째 값 + 마지막 값 ) * 갯수 / 2 

(1+10) * 10 / 2 = 55

Posted by 비니미니파
Python2021. 11. 3. 16:04

def 함수명(파라미터1, 파라미터2 ....)

# sum 함수 선언
def sum(x,y):
    return x+y

# sum 함수 호출
sum(3,4)

 

간단하죠 ^^

Posted by 비니미니파
Python2021. 11. 3. 15:55
import matplotlib.pyplot as plt  
import numpy as np

# 선그래프
plt.plot([1,2,3,4])
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()

# 선모양
x = np.arange(0., 10., 0.3) # 0에서 10미만 0.3 증가
y = x**2                    # x의 2 제곱
line = plt.plot(x, y)
plt.setp(line, color='r', linewidth=3.0)  # 선모양
plt.show()

Posted by 비니미니파
Python2021. 8. 5. 17:53

시작일~종료일 까지 반복 하는 Python 코드

datetime, timedelta

 

from datetime import datetime, timedelta

# 시작일,종료일 설정
start = "2021-08-01"
last = "2021-08-04"

# 시작일, 종료일 datetime 으로 변환
start_date = datetime.strptime(start, "%Y-%m-%d")
last_date = datetime.strptime(last, "%Y-%m-%d")

# 종료일 까지 반복
while start_date <= last_date:
    dates = start_date.strftime("%Y-%m-%d")
    print(dates)

    # 하루 더하기
    start_date += timedelta(days=1)

 

Posted by 비니미니파