반응형

[python] How to write to an HTML file in Python

https://www.kite.com/python/answers/how-to-write-to-an-html-file-in-python

 

Kite - Free AI Coding Assistant and Code Auto-Complete Plugin

Code faster with Kite’s AI-powered autocomplete plugin for over 16 programming languages and 16 IDEs, featuring Multi-Line Completions. Works 100% locally.

www.kite.com

USE open() AND file.write() TO WRITE TO AN HTML FILE

Use open(file, mode) with mode as "w" to create a new HTML file file or write to an existing one. Use file.write(data) to write data to the file. Use file.close() to close the file after writing.

text = '''
<html>
    <body>
        <h1>Heading</h1>
    </body>
</html>
'''
file = open("sample.html","w")
file.write(text)
file.close()
SAMPLE.HTML
<html>
    <body>
        <h1>Heading</h1>
    </body>
</html>
반응형
반응형

mpld3 - Bringing Matplotlib to the Browser

https://mpld3.github.io/install.html

 

Installing mpld3 — Bringing Matplotlib to the Browser

Dependencies The mpld3 package is compatible with Python versions 2.6, 2.7, 3.3, and 3.4. It requires matplotlib version 1.3+ and jinja2 version 2.7+. Optionally, mpld3 can be used within the IPython notebook, and requires IPython version 1.0+, and prefera

mpld3.github.io

 mpld3는 매트플롯립과 d3js를 사용해서 웹의 인터랙티브 데이터 시각화 를 가능하도록 만드는 것이 목적이라고 하네요. 간단하게, matpllitb의 그래픽을 html코드로(코드를 뜯어보면, 사실 거의 d3js 코드입니다만), 변환해줍니다. 이걸 가지고, 차트 같은 것을 좀 더 편하게 변환할 수 있겠죠.

https://anaconda.org/conda-forge/mpld3

Installers

Info: This package contains files in non-standard labels.

conda install 

  •  linux-64  v0.3
  •  win-32  v0.3
  •    noarch  v0.5.7
  •  osx-64  v0.3
  •  win-64  v0.3
To install this package with conda run one of the following:
conda install -c conda-forge mpld3
conda install -c conda-forge/label/gcc7 mpld3
conda install -c conda-forge/label/cf201901 mpld3
conda install -c conda-forge/label/cf202003 mpld3
반응형
반응형

networkx - Graph Layout

 

Graph Layout

Node positioning algorithms for graph drawing.

For random_layout() the possible resulting shape is a square of side [0, scale] (default: [0, 1]) Changing center shifts the layout by that amount.

For the other layout routines, the extent is [center - scale, center + scale] (default: [-1, 1]).

Warning: Most layout routines have only been tested in 2-dimensions.

bipartite_layout(G, nodes[, align, scale, ...]) Position nodes in two straight lines.
circular_layout(G[, scale, center, dim]) Position nodes on a circle.
kamada_kawai_layout(G[, dist, pos, weight, ...]) Position nodes using Kamada-Kawai path-length cost-function.
planar_layout(G[, scale, center, dim]) Position nodes without edge intersections.
random_layout(G[, center, dim, seed]) Position nodes uniformly at random in the unit square.
rescale_layout(pos[, scale]) Returns scaled position array to (-scale, scale) in all axes.
rescale_layout_dict(pos[, scale]) Return a dictionary of scaled positions keyed by node
shell_layout(G[, nlist, rotate, scale, ...]) Position nodes in concentric circles.
spring_layout(G[, k, pos, fixed, ...]) Position nodes using Fruchterman-Reingold force-directed algorithm.
spectral_layout(G[, weight, scale, center, dim]) Position nodes using the eigenvectors of the graph Laplacian.
spiral_layout(G[, scale, center, dim, ...]) Position nodes in a spiral layout.
multipartite_layout(G[, subset_key, align, ...]) Position nodes in layers of straight lines.

 

https://networkx.org/documentation/latest/reference/drawing.html#module-networkx.drawing.layout

 

Drawing — NetworkX 2.7rc1.dev0 documentation

Drawing NetworkX provides basic functionality for visualizing graphs, but its main goal is to enable graph analysis rather than perform graph visualization. In the future, graph visualization functionality may be removed from NetworkX or only available as

networkx.org

반응형
반응형

Choosing Colormaps in Matplotlib

https://matplotlib.org/stable/tutorials/colors/colormaps.html

 

Choosing Colormaps in Matplotlib — Matplotlib 3.5.1 documentation

Colormaps are often split into several categories based on their function (see, e.g., [Moreland]): First, we'll show the range of each colormap. Note that some seem to change more "quickly" than others. Sequential2 Many of the \(L^*\) values from the Seque

matplotlib.org

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from colorspacious import cspace_converter
cmaps = {}

gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))


def plot_color_gradients(category, cmap_list):
    # Create figure and adjust figure height to number of colormaps
    nrows = len(cmap_list)
    figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22
    fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh))
    fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh,
                        left=0.2, right=0.99)
    axs[0].set_title(f'{category} colormaps', fontsize=14)

    for ax, name in zip(axs, cmap_list):
        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
        ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10,
                transform=ax.transAxes)

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axs:
        ax.set_axis_off()

    # Save colormap list for later.
    cmaps[category] = cmap_list

 

plot_color_gradients('Perceptually Uniform Sequential',
                     ['viridis', 'plasma', 'inferno', 'magma', 'cividis'])

plot_color_gradients('Sequential',
                     ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
                      'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
                      'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'])

 

 

 

 

 

반응형
반응형

연관규칙분석(Association Rule Analysys)이란 그냥 나열되어 있는 원본 데이터들에 대해서 데이터들간의 연관관계를 탐색하는 무방향성 데이터마이닝 기법중에 하나이다.

보통 마트의 고객들이 구매한 상품간의 연관관계를 찾을 때 많이 사용되는 분석기법이라서 '장바구니 분석' 이라고도 한다.  예를 들어.. 남성 고객이 마트에 가서 구매한 품목을 보니깐 맥주와 기저귀를 같이 구매하는 경우가 많이 나타나면 마트 진열대에 맥주와 기저귀를 같이 배치하는 한다던지 (매장진열), 또 라면을 살때 스윙칩을 같이 사는 형태가 많이 발견된다면 이 두 상품을 합친 패키지 상품을 개발한다던지..(GS25의 오모리김치찌게맛 스윙칩) 여성 고객은 편의점에서 주로 우유와 커피라서 편의점에 들어가면 진열대 가장 잘 보이는 곳에 우유와 커피 제품을 진열하는 것을 볼수 있는데 이런 것들이 모두 연관규칙분석을 통해 효과적인 매장 진열, 패키지상품의 개발, 교차판매 전략수립에 많이 이용된다.

 

연관규칙의 특징

특징 설명
장바구니 분석 구매 내역 분석을 통해 동시에 구매될 가능성이 있는 상품의 연관관계를 찾는다.
또는 A제품을 구매 후 B제품을 구매할 가능성이 높은 경우 해당 제품들을 나란히
진열을 하는 경우.
자율학습기법
(Unsupervised Learning)
자율학습의 반대말인 지도학습을 먼저 설명하면 지도학습(supervised Learning)이란 이미 목표변수, 목표값이 정해진 상태에서 데이터를 분석하는 것을 말하며, 자율학습이란 목표변수, 결과값을 모르는 상태에서 데이터를 분석해서 데이터간의 관계를 분석해서 결과값을 도출해내는 분석기법이다. 자율학습기법에 대표적인 것이 바로 연관규칙분석이다.  
   1) 자율학습기법 (Unsupervised Learning)
        - 연관규칙분석
        - 군집분석 :  수많은 데이터들을 2개그룹, 3개그룹 등으로 분류
   2) 지도분석기법 (Supervised Learning)
        - 신경망 분석
        - 의사결정나무 분석
        - 사례기반
        - 로지스틱 회귀분석
탐색적 기법 조건반응(if then else)으로 표현되므로 이해가 쉬윔
 - 만일 A가 일어난다면 B가 일어난다. 
 - 상품 A를 구매하면 상품 B도 구매를 한다.
 - 어떤 Item 집합의 존재가 다른 Item 집합의 존재를 암시
즉 함께 구매하는 상품의 조합이나 패턴을 파악
목적변수 미존재 목적변수(Target Variable) 없이 특성의 조합으로 규칙을 표현하며, 특정한 변수가 아닌 모든 변수 또는 특성에 대하여 예측
규칙간의 독립성 규칙들 간에는 서로 영향을 주지 않기 때문에 하나의 고객이 여러 개의
규칙에 해당 될 수 있음


연관규칙 도출과정

Apyori - 연관규칙분석(Association Rule Analysys)

Apyori is a simple implementation of Apriori algorithm with Python 2.7 and 3.3 - 3.5, provided as APIs and as commandline interfaces.

https://github.com/ymoch/apyori

Installation

Choose one from the following.

  • Install with pip pip install apyori.
  • Put apyori.py into your project.
  • Run python setup.py install.

 

https://anaconda.org/auto/apriori   

 

 

연관규칙 측정기준

< 출처 : 정보관리기술사 118회 모임 - 두드림 >

 

연관규칙의 결과 유형

결과유형 설명
Useful Result 분석결과가 마케팅 측면에서 유용한, 쓸만한 결과가 나옴.
예) 맥주와 기저귀 상품과의 구매관계
Trivial Result 어떤 새로운 분석결과가 아닌 기존 마케팅 정책에 의해 연관성이 높게 나온 경우
먼가 새롭게 발견된 구매패턴이 아니고 기존 마케팅 활동 결과로서 예상이 되는
결과를 말함.
예) 정비계약을 맺은 고객이 많은 설비를 구매하더라..  -> 이는 정비계약에 의해
     자연스럽게 따라오는 설비 구매 형태일뿐
Inexplicable Result
(설명할수 없는 결과)
의미를 발견하기 위해 많은 고민이 필요한 경우
예) 새로 철물점을 개업하면 화장시 문고리가 많이 팔림.. -> 연관관계가 있는건지
     고민이 필요함..



활용분야

분야 내용
교차판매 (Cross Selling)
묶음판매 (Bundling)
A제품을 구매한 고객이 B제품을 추가로 구매할 수 있도록 유도하는 전략에 사용
예) 맥주와 기저귀, 양복과 넥타이
상품진열 고객의 구매패터을 고려하여 매대상품을 진열
예) 편의점에 제일 잘보이는 곳에 우유와 커피를 나란히 진열
부정탐지 (Fraud Detection) 신용카드나 보험금 수령 패턴을 분석하여 도난카드나 보험사기 행위를 적발
Catalog Design 상품의 배치문제, 패키지 상품의 구성, 쿠폰발행, 카탈로그의 구성, 신상품의카테고리 설정 등에 활용 가능
첨부 우편물 우편물 내용과 첨부파일과이 관계분석


연관규칙의 주의점


1. 연관규칙분석은 원인과 결과 즉 인과관계를 찾는 게 아니라는 것이다. 맥주가 원인이고 기저귀가 결과라는
   뜻이 아니라 , 맥주와 기저귀가 같이 조합을 이룬다는 뜻이다..
2. 연관규칙 즉 자율탐색기법(Unsupervised Learning) 은 목표변수(Target Variable) 이 없다.. 이 말이  
   무슨 말이냐면.. 연관규칙 분석에 의해 나온 결과값에 대해서 맞다, 안맞다 를 판단하는게 아니라는
   뜻이다. 예를 들어 맥주를 산 고객은 기저귀를 같이 구매를 한다 라고 결과가 나왔지만 이 것이
   정답이 아닐수도.. 즉 맥주를 산 고객이 무조건 기저귀를 사는 것은 아니라는 뜻이다.

 

반응형
반응형

프로젝트 가상공간에 들어가서

> conda install -c anaconda networks

 

https://pypi.org/project/networkx/

 

networkx

Python package for creating and manipulating graphs and networks

pypi.org

Installers  - https://anaconda.org/anaconda/networkx

conda install 

  •  linux-ppc64le  v2.2
  •  linux-64  v2.2
  •  win-32  v2.2
  •    noarch  v2.6.3
  •  osx-64  v2.2
  •  linux-32  v2.2
  •  win-64  v2.2
To install this package with conda run:
conda install -c anaconda networkx
반응형
반응형

 

Mlxtend (machine learning extensions) is a Python library of useful tools for the day-to-day data science tasks.

 

https://github.com/rasbt/mlxtend 

 

GitHub - rasbt/mlxtend: A library of extension and helper modules for Python's data analysis and machine learning libraries.

A library of extension and helper modules for Python's data analysis and machine learning libraries. - GitHub - rasbt/mlxtend: A library of extension and helper modules for Python's data an...

github.com

Installing mlxtend

PyPI

To install mlxtend, just execute

pip install mlxtend  

Alternatively, you could download the package manually from the Python Package Index https://pypi.python.org/pypi/mlxtend, unzip it, navigate into the package, and use the command:

python setup.py install

Conda

If you use conda, to install mlxtend just execute

conda install -c conda-forge mlxtend 

반응형
반응형

pandas documentation - python

 

https://pandas.pydata.org/docs/index.html

 

pandas documentation — pandas 1.4.1 documentation

The reference guide contains a detailed description of the pandas API. The reference describes how the methods work and which parameters can be used. It assumes that you have an understanding of the key concepts.

pandas.pydata.org

 

반응형

+ Recent posts