# drawSinWave.py
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
def plotSinWave(**kwargs):
"""
plot sine wave
y = a sin(2 pi f t + t_0) + b
"""
endTime = kwargs.get("endTime", 1)
sampleTime = kwargs.get("sampleTime", 0.01)
amp = kwargs.get("amp", 1)
freq = kwargs.get("freq", 1)
startTime = kwargs.get("startTime", 0)
bias = kwargs.get("bias", 0)
figsize = kwargs.get("figsize", (12, 6))
time = np.arange(startTime, endTime, sampleTime)
result = amp + np.sin(2 * np.pi * freq * time + startTime) +bias
plt.figure(figsize=(12, 6))
plt.plot(time, result)
plt.grid(True)
plt.xlabel("time")
plt.ylabel("sin")
plt.title(str(amp) + "*sin(2*pi" + str(freq) + "*t+" +
str(startTime) + ")+" + str(bias))
plt.show()
if __name__ == "__main__":
print("Hello World")
plotSinWave(amp=1, endTime=2)
# set_matplotlib_hangul.py
import platform
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
path = "C:/Window/Fonts/malgun.ttf"
if platform.system() == "Darwin":
print("Hangle OK in your MAC.")
rc("font", family="AppleGothic")
elif platform.system() == "Windows":
font_name = font_manager.FontProperties(fname=path).get_name()
print("Hangle OK in your Windows.")
rc("font", family=font_name)
else:
print("Sorry, Unkwnown System.")
plt.rcParams["axes.unicode_minus"] = False
따로 설치하지 않고 colab을 통해서 실습했다.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from prophet import Prophet
# from fbprophet import Prophet ❌ ➡ 이름이 prophet으로 변경되었다고 함
from pandas_datareader import data
time = np.linspace(0, 1, 365*2)
result = np.sin(2*np.pi*12*time) + time + np.random.randn(365*2)/4
ds = pd.date_range("2022-01-01", periods=365*2, freq="D")
df = pd.DataFrame({"ds": ds, "y": result})
df["y"].plot(figsize=(10, 6))
m = Prophet(yearly_seasonality=True, daily_seasonality=True)
m.fit(df)
# 30일간의 데이터 예측
future = m.make_future_dataframe(periods=30)
forecast = m.predict(future)
m.plot(forecast)
pinkwink_web = pd.read_csv("경로",
encoding="utf-8",
thousands=",",
names=["date", "hit"],
index_col=0
)
pinkwink_web = pinkwink_web[pinkwink_web["hit"].notnull()]
pinkwink_web["hit"].plot(figsize=(12, 4), grid=True);
time = np.arange(0, len(pinkwink_web)) # x축 값
traffic = pinkwink_web["hit"].values
# time[-1] = 364
fx = np.linspace(0, time[-1], 1000)
# 에러를 계산할 함수
def error(f, x, y):
return np.sqrt(np.mean((f(x) - y) ** 2))
fp1 = np.polyfit(time, traffic, 1)
f1 = np.poly1d(fp1)
fp2 = np.polyfit(time, traffic, 2)
f2 = np.poly1d(fp2)
fp3 = np.polyfit(time, traffic, 3)
f3 = np.poly1d(fp3)
fp15 = np.polyfit(time, traffic, 15)
f15 = np.poly1d(fp15)
print(error(f1, time, traffic))
print(error(f2, time, traffic))
print(error(f3, time, traffic))
print(error(f15, time, traffic))
>>>
430.8597308110963
430.6284101894695
429.53280466762925
330.4777305877038
1차, 2차, 3차식이 별 차이 없으니 가장 단순한 1차식을 사용하는 게 좋다.
plt.figure(figsize=(12, 4))
plt.scatter(time, traffic, s=10)
plt.plot(fx, f1(fx), lw=4, label="f1")
plt.plot(fx, f2(fx), lw=4, label="f2")
plt.plot(fx, f3(fx), lw=4, label="f3")
plt.plot(fx, f15(fx), lw=4, label="f15")
plt.grid(True, linestyle="-", color="0.75")
plt.legend(loc=2)
plt.show()
df = pd.DataFrame({"ds": pinkwink_web.index, "y": pinkwink_web["hit"]})
df.reset_index(inplace=True)
# 날짜 형식 맞추기
df["ds"] = pd.to_datetime(df["ds"], format="%y. %m. %d.")
del df["date"]
# 학습시키기
m = Prophet(yearly_seasonality=True, daily_seasonality=True)
m.fit(df)
# 60일간의 데이터 예측
# 예측 결과는 상한/하한 범위를 포함해서 얻어짐
futrue = m.make_future_dataframe(periods=60)
forecast = m.predict(future)
m.plot(forecast)
코랩에서 제대로 그려지지 않아서 강의 자료를 참고했다.
m.plot_components(forecast)