Пример #1
0
def show_time(request):
    fig = plt.figure()
    ax = fig.add_subplot(121)
    data = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data = pd.DataFrame(data)

    dt_jy = data.groupby('주야')
    dtjy = dt_jy['발생년'].count()

    labels1 = ['야', '주']

    ax = dtjy.plot(kind='pie', title='사고유형', figsize=(18, 6), fontsize=17, autopct='%.1f%%')

    ax = fig.add_subplot(122)
    data_df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data = pd.DataFrame(data_df)

    data["발생시"].unique()
    data_si = data["발생시"].value_counts()
    data_si.shape[0]
    for i in range(data_si.shape[0]):
        si = sns.countplot(data=data, x="발생시")
    for i in range(data_si.shape[0]):
        si.text(x=i, y=data_si[i], s=data_si[i], horizontalalignment='center')

    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    response = HttpResponse(buf.getvalue(), content_type="image/png")
    response['Content-Length'] = str(len(response.content))
    return response
Пример #2
0
def road_shape(request):
    fig = plt.figure()
    ax = fig.add_subplot(121)
    df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv", encoding='utf-8')
    df = pd.DataFrame(df)
    data3=df['도로형태'].value_counts()

    ax = data3.plot(kind='pie', figsize=(15, 10), legend=False, autopct='%1.2f%%', fontsize=15)
    plt.xticks(rotation=0)

    ax = fig.add_subplot(122)
    df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv", encoding='utf-8')
    df = pd.DataFrame(df)
    data4 = df[df["가해자법규위반"] == "과속"].loc[:, ["가해자법규위반", "도로형태"]].value_counts()

    ax = data4.plot(kind='bar', figsize=(15, 7), legend=False, fontsize=15)
    plt.xticks(rotation=0)

    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    fig.clear()
    response = HttpResponse(buf.getvalue(), content_type="image/png")
    response['Content-Length'] = str(len(response.content))
    return response
Пример #3
0
def patients_chart(request):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    data = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv", encoding='utf-8')
    df = pd.DataFrame(data)

    chung_df = df.loc[df['발생지시도'] == '충남', ['발생년', '사망자수', '부상자수', '중상자수', '경상자수']]
    chung_group = chung_df.groupby(["발생년"])[["사망자수", "부상자수", "중상자수", "경상자수"]].sum()

    color = "red", "pink", "sandybrown", "peachpuff"
    ax = chung_group.plot(kind='bar', title='환자유형', figsize=(12, 5), legend=True, fontsize=18, color=color)

    ax.set_xlabel('발생년도', fontsize=12)  # x축 정보 표시

    plt.xticks(rotation=45)  # 가로축 텍스트 회전 (세로로 보이던거 수정)
    ax.set_ylabel('사고수', fontsize=12)  # y축 정보 표시
    ax.legend(['사망자수', '부상자수', '경상자수', '중상자수'], fontsize=12)

    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    fig.clear()
    response = HttpResponse(buf.getvalue(), content_type="image/png")
    response['Content-Length'] = str(len(response.content))
    return response
Пример #4
0
def law_violations(request):
    fig = plt.figure()
    ax = fig.add_subplot(121)
    df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv", encoding='utf-8')

    data1 = df['가해자법규위반'].value_counts()

    ax = data1.plot(kind='pie', figsize=(15, 10), legend=False, autopct='%1.2f%%', fontsize=12)
    plt.xticks(rotation=0)

    ax = fig.add_subplot(122)

    df = pd.read_csv('C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv', encoding='utf-8')
    data2 = df['가해자법규위반'].value_counts()

    ax1 = data2.plot(kind='bar', figsize=(25, 7), fontsize=9, color='pink')
    ax1.set_xlabel('')
    plt.xticks(rotation=360)  # 가로축 텍스트 회전 (세로로 보이던거 수정)
    ax1.set_ylabel('')

    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    fig.clear()
    response = HttpResponse(buf.getvalue(), content_type="image/png")
    response['Content-Length'] = str(len(response.content))
    return response
Пример #5
0
def chart_hap(request):
    fig = plt.figure()
    ax = fig.add_subplot(122)
    data_df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data_df = pd.DataFrame(data_df)

    selectdata3 = data_df.groupby('발생년')
    selectdata4 = selectdata3['발생년'].count()

    labels2 = ['2015', '2016', '2017', '2018', '2019']
    ax = selectdata4.plot(kind='pie', title='사고유형', figsize=(18, 6), fontsize=17, autopct='%.1f%%')

    ax = fig.add_subplot(121)
    data = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data = pd.DataFrame(data)

    selectdata5 = data.groupby('발생년')
    selectdata6 = selectdata5['발생년'].count()
    x = np.arange(5)
    years = ['2015', '2016', '2017', '2018', '2019']
    values = selectdata6

    plt.bar(x, values)
    plt.xticks(x, years)

    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    fig.clear()
    response = HttpResponse(buf.getvalue(), content_type="image/png")
    response['Content-Length'] = str(len(response.content))
    return response
Пример #6
0
def show_images(images, labels, preds):
    plt.figure(figsize=(8, 4))
    for i, image in enumerate(images):
        plt.subplot(1, 6, i + 1, xticks=[], yticks=[])
        image = image.numpy().transpose((1, 2, 0))
        mean = np.array([0.485, 0.456, 0.406])
        std = np.array([0.229, 0.224, 0.225])
        image = image * std + mean
        image = np.clip(image, 0., 1.)
        plt.imshow(image)
        col = 'green'
        if preds[i] != labels[i]:
            col = 'red'

        plt.xlabel(f'{class_names[int(labels[i].numpy())]}')
        plt.ylabel(f'{class_names[int(preds[i].numpy())]}', color=col)
    plt.tight_layout()
    plt.show()
Пример #7
0
def chart_hap2(request):
    fig = plt.figure()
    ax = fig.add_subplot(212)  # ax=도화지
    data_df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data_df = pd.DataFrame(data_df)

    df1 = data_df.loc[data_df['발생지시도'] == '충남', ['발생년', '사고유형_대분류']]
    df1_group = df1.groupby("사고유형_대분류")['발생년'].count()
    colors = ['#ffc000', '#8fd9b6', '#d395d0']
    wedgeprops = {'width': 0.7, 'edgecolor': 'w', 'linewidth': 5}


    ax = df1_group.plot(kind='pie', title='사고유형', figsize=(18, 6), fontsize=17, autopct='%.1f%%', colors=colors,
                        wedgeprops=wedgeprops)

    ax.set_ylabel('', fontsize=5)

    ax = fig.add_subplot(122)  # ax=도화지
    data_df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data_df = pd.DataFrame(data_df)
    df3 = data_df.loc[data_df['발생지시도'] == '충남', ['발생년', '가해자_당사자종별']]
    df3_group = df3.groupby("가해자_당사자종별")['발생년'].count()
    colors1 = ['thistle', 'mistyrose', 'lightpink']

    ax2 = df3_group.plot(kind='pie', title='가해자차종', figsize=(18, 6), fontsize=17, autopct='%.1f%%', colors=colors1)

    ax2.set_ylabel('', fontsize=5)

    ax = fig.add_subplot(121)  # ax=도화지
    data_df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data_df = pd.DataFrame(data_df)
    df5 = data_df.loc[data_df['발생지시도'] == '충남', ['발생년', '피해자_당사자종별']]
    df5_group = df5.groupby("피해자_당사자종별")['발생년'].count()
    df5_group = df5_group.sort_values(ascending=False)
    colors2 = ['darkturquoise', 'cadetblue', 'powderblue', 'lightblue', 'skyblue', 'lightskyblue', 'lightsteelblue',
              'aliceblue', 'linen']

    ax3 = df5_group.plot(kind='pie', title='피해자유형', figsize=(18, 6), fontsize=12, autopct='%.1f%%', colors=colors2)

    ax3.set_ylabel('', fontsize=5)
    ax3.set_ylabel('', fontsize=5)

    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    fig.clear()
    response = HttpResponse(buf.getvalue(), content_type="image/png")
    response['Content-Length'] = str(len(response.content))
    return response
Пример #8
0
def chart_casualtie(request):
    fig = plt.figure()
    ax = fig.add_subplot(121)  # ax=도화지
    data_df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data_df = pd.DataFrame(data_df)
    df4 = data_df.loc[data_df['발생지시도']=='충남',['발생년','발생지시군구']]
    df4_group = df4.groupby("발생지시군구")['발생년'].count()
    df4_group = df4_group.sort_values(ascending=True)
    color = 'rosybrown'

    ax = df4_group.plot(kind='bar', title='시/군별 사고수', figsize=(12, 5), fontsize=13, color=color)
    ax.set_xlabel('', fontsize=12)  # x축 정보 표시

    plt.xticks(rotation=45)  # 가로축 텍스트 회전 (세로로 보이던거 수정)
    ax.set_ylabel('', fontsize=12)  # y축 정보 표시

    ax = fig.add_subplot(122)  # ax=도화지
    data_df = pd.read_csv("C:/djangowork1/accidentsite/static/어린이 사망교통사고 정보(2015~2019년).csv")

    data_df = pd.DataFrame(data_df)
    df2 = data_df.loc[data_df['발생지시도']=='충남',['발생년','요일']]
    df2_group = df2.groupby("요일")["발생년"].count()
    df2_group = df2_group.sort_values(ascending=False)
    color = 'tan'
    ax5 = df2_group.plot(kind='bar', title='요일별 사고수', figsize=(12, 5), fontsize=18, color=color)
    ax5.set_xlabel('', fontsize=12)  # x축 정보 표시

    plt.xticks(rotation=360)  # 가로축 텍스트 회전 (세로로 보이던거 수정)
    ax5.set_ylabel('', fontsize=12)  # y축 정보 표시

    buf = io.BytesIO()
    canvas = FigureCanvasAgg(fig)
    canvas.print_png(buf)
    fig.clear()
    response = HttpResponse(buf.getvalue(), content_type="image/png")
    response['Content-Length'] = str(len(response.content))
    return response
Пример #9
0
        if size == 1:
            for line in content:
                k_array = line.split(" ")

            file_graph = str(sys.argv[2])

            if os.path.exists(file_graph):
                # if file exist
                with open(file_graph) as f:
                    content = f.readlines()
                # read each line
                content = [x.strip() for x in content]
                ratio = NULL
                size = len(content)
                if size == 1:
                    for line in content:
                        ratio = line.split(" ")
                    list_ratio = []
                    for i in ratio:
                        list_ratio.append(float(i))
                    list_k_array = []
                    for i in k_array:
                        list_k_array.append(float(i))
                    plt.clf()
                    plt.figure(figsize=(16, 10))
                    plt.ylabel("Ratio")
                    plt.xlabel("k_degree")
                    plt.plot(list_k_array, list_ratio, 'r--')
                    plt.title("Graph friend 1000 10 100")
                    plt.savefig("ratio_fakedataset.png", dpi=120)
model.add(Dense(output_size, activation='sigmoid'))
model.compile(optimizer='adam', loss='mse')

#------------------------------------------------------训练-------------------------------------------------
epochs = 15
batch_size = 128
history = model.fit(x_train, x_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, x_test))

#-----------------------------------------------------查看解码效果--------------------------------------------
decoded_imgs = model.predict(x_test)
n = 10
plt.figure(figsize=(20, 6))
for i in range(n):
    # 原图
    ax = plt.subplot(3, n, i+1)
    plt.imshow(x_test[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)


    # 解码效果图
    ax = plt.subplot(3, n, i+n+1)
    plt.imshow(decoded_imgs[i].reshape(28, 28))
    plt.gray()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
Пример #11
0
rc('font', family='NanumBarunGothic')

wordcloud = WordCloud(
    font_path='/content/CookieRun Regular.ttf',  # 맥에선 한글폰트 설정 잘해야함.
    background_color='white',  # 배경 색깔 정하기
    colormap='Accent_r',  # 폰트 색깔 정하기
    width=800,
    height=800)

wordcloud_words = wordcloud.generate_from_frequencies(words)
array = wordcloud.to_array()
print(type(array))  # numpy.ndarray
print(array.shape)  # (800, 800, 3)

fig = plt.figure(figsize=(10, 10))
plt.imshow(array, interpolation="bilinear")
plt.axis('off')
plt.show()
fig.savefig('business_anlytics_worldcloud.png')
for sentence in lists:
    morphs.append(twitter.pos(sentence))
print(morphs)

noun_adj_adv_list = []
for sentence in morphs:
    for word, tag in sentence:
        if tag in ['Noun'] and ("것" not in word) and ("내" not in word) and (
                "나" not in word) and ("수" not in word) and (
                    "게" not in word) and ("말" not in word):
            noun_adj_adv_list.append(word)