<jupyter_start><jupyter_text>Import data<jupyter_code>import gdown 

url = 'https://drive.google.com/uc?id=1CxOcvyFlx2V-8ubpRuVZclOBUYFPe_t6'
output = 'MLTollsStackOverflow.csv'
gdown.download(url, output)                                                                  
import pandas as pd
df = pd.read_csv("MLTollsStackOverflow.csv")
df["month"] = pd.to_datetime(df["month"], format="%y-%b")
df = df.set_index("month")
python = df["python"].to_frame()
train_len = 102
train = python.iloc[:train_len]
test = python.iloc[train_len:]<jupyter_output><empty_output><jupyter_text>Turn Data into Time Series<jupyter_code># !pip install kats
# !pip install localpip 
# !localpip install fbprophet
from kats.consts import TimeSeriesData
ts = TimeSeriesData(train.reset_index(), time_col_name="month")

ts.plot(cols=["python"])<jupyter_output><empty_output><jupyter_text>Forecasting  Facebook Prophet<jupyter_code>from kats.models.prophet import ProphetModel, ProphetParams

params = ProphetParams(seasonality_mode="multiplicative")
m = ProphetModel(ts, params)
m.fit()
fcst = m.predict(steps=30, freq="MS")
fcst.head()
m.plot()
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(12, 7))
train.plot(ax=ax, label="train", color="black")
test.plot(ax=ax, color="black")
fcst.plot(x="time", y="fcst", ax=ax, color="blue")
ax.fill_between(test.index, fcst["fcst_lower"], fcst["fcst_upper"], alpha=0.5)
ax.get_legend().remove()<jupyter_output><empty_output><jupyter_text>Holt-Winters<jupyter_code>from kats.models.holtwinters import HoltWintersParams, HoltWintersModel
import warnings
warnings.simplefilter(action='ignore')

params = HoltWintersParams(
            trend="add",
            seasonal="mul",
            seasonal_periods=12,
        )
m = HoltWintersModel(
    data=ts, 
    params=params)

m.fit()
fcst = m.predict(steps=30, alpha = 0.1)
m.plot()<jupyter_output><empty_output><jupyter_text>Detect change point<jupyter_code>from IPython.core.pylabtools import figsize
from kats.consts import TimeSeriesData, TimeSeriesIterator
from kats.detectors.cusum_detection import CUSUMDetector
import matplotlib.pyplot as plt
figsize(15, 7)
detector = CUSUMDetector(ts)

change_points = detector.detector(change_directions=["increase", "decrease"])

for change_point in change_points:
    print("The change point is on", change_point[0].start_time)

# plot the results
plt.xticks(rotation=45)
detector.plot(change_points)
plt.show()
def get_ts(topic: str):
    return TimeSeriesData(df[topic].to_frame().reset_index(), time_col_name="month")
def detect_change_point(topic: str):
    ts = get_ts(topic)
    detector = CUSUMDetector(ts)

    change_points = detector.detector()
    for change_point in change_points:
        print("The change point is on", change_point[0].start_time)

    # plot the results
    plt.xticks(rotation=45)
    detector.plot(change_points)
    plt.show()
detect_change_point("machine-learning")
detect_change_point("neural-network")
detect_change_point("deep-learning")
detect_change_point("jupyter")
detect_change_point("plotly")
detect_change_point("H2o")
detect_change_point("Colab")<jupyter_output>The change point is on 2016-12-01 00:00:00<jupyter_text>Outlier Detection<jupyter_code>df["nlp"].plot()
ts = get_ts("nlp")
from kats.detectors.outlier import OutlierDetector

ts_outlierDetection = OutlierDetector(ts, "additive")
ts_outlierDetection.detector()
outlier_range1 = ts_outlierDetection.outliers[0]
print(f"The outliers range from {outlier_range1[0]} to {outlier_range1[1]}")<jupyter_output>The outliers range from 2018-01-01 00:00:00 to 2019-03-01 00:00:00<jupyter_text>Time Series Features<jupyter_code>ts
from kats.tsfeatures.tsfeatures import TsFeatures

model = TsFeatures()

output_features = model.transform(ts)
output_features<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12627986348122866, 'fraction_numerical': 0.020477815699658702, 'mean_word_length': 6.215909090909091, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '530625', 'license': 'MIT', 'n_tokens_mistral': 1430, 'n_tokens_neox': 1346, 'n_words': 234, 'path': 'Data Science and Machine Learning/Time Series/Time Series with FBProphet and Outlier Detection - kats/Time Series with FBProphet and Outlier Detection - kats.ipynb', 'repo_name': 'okara83/Becoming-a-Data-Scientist', 'size': '3809'}