Python3

silhouette_samples が Memory Errorになったときの対応

from sklearn.metrics import silhouette_samples silhouette_samples で、Memory Error にならない関数を作ってくれている。 stackoverflow.com

matplotlibについて

matplotlib について、一回tutorial やったほうが良いかも Tutorials — Matplotlib 2.2.2 documentation

matplotまとめてあったので、引用

python-remrin.hatenadiary.jp

Django の models に対応したテーブルを MySQL から grep する方法

以下のコマンドで、取り出す。 mysql -uroot -N information_schema -e "select table_name from tables where table_schema = 'tablename' and table_name like 'prefix_%'" > table.txt

tf の mnist をニューラルネットワークで分析

正解率が90%と低めに出た。。原因は今度調べよう import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) mnist.train.images.shape => (55000, 784) n_feat…

word2vecすごいぞ

結構すごい。。表記ゆれとかも吸収できそう。 from gensim.models import word2vec ls = [] for row in df_id['review_comment'].values[:100000]: ls.append(_split_to_rawwords(row)) model = word2vec.Word2Vec(ls, size=500, window=5, min_count=5, wor…

LDA(Latent Dirichlet Allocation) でのトピック抽出 でレビュー分析

レビューの分析方法をまとめる。 import os import glob import sys from datetime import (datetime, date, timedelta) import logging import re import shutil import tempfile import pandas as pd import numpy as np from scipy.sparse.csc import csc…

pythonのscipyでsparseな行列の変換

sparseな行列についての実装 import numpy as np from scipy.sparse import coo_matrix ) a = np.arange(30).reshape(10,3) print(a) [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14] [15 16 17] [18 19 20] [21 22 23] [24 25 26] [27 28 29]] b, c, d …

GCPでのレコメンド実装について

Building a Recommendation System in TensorFlow: Overview | Solutions | Google Cloud

pandasを使うときに利用したサイト

applyとかassignとかpipeとかapplymapとか。numpyで対応していたところもあって知らなかった。 qiita.com stackoverflow.com stackoverflow.com

python と java について、vim の mode line を設定する

tab で 4 space 入れる方法。 #!/usr/bin/env python # -*- encoding:utf-8 -*- # vim:tabstop=4:shiftwidth=4:expandtab print('aaa') /* vim:set ts=4 sw=4 et ws is nowrap ft=java fenc=utf-8 ff=dos: */ class JSample13_1{ public static void main(St…

クラスタリング : DBSCAN の実装

クラスタリングアルゴリズムの中で、クラスタが球状という前提を持たずに、 クラスタラベルを割り当てる。 from sklearn.datasets import make_moons X, y = make_moons( n_samples=200, noise=0.05, random_state=0 ) plt.scatter(X[:, 0 ], X[:, 1]) plt.t…

ボトムアップ式のクラスタリングのグループ化

データ作成 shape: (5, 3) のランダム行列を作成 import pandas as pd import numpy as np np.random.seed(123) variables = ['X', 'Y', 'Z'] labels = ['ID_0', 'ID_1', 'ID_2', 'ID_3', 'ID_4'] X = np.random.random_sample([5, 3])*10 ## pandas のデー…

教師なしデータのクラスタ分析の検証

## クラスタリングのサンプルを作成 from sklearn.datasets import make_blobs X, y = make_blobs( n_samples=150, n_features=2, centers=3, cluster_std=0.5, shuffle=True, random_state=True ) ## クラスタリングを描画 plt.scatter(X[:, 0], X[:, 1], c…

アンサンブル分類器の実装

一般的に、アンサンブル分類器の方が、個別の分類器より性能が高い from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import ( StandardScaler, LabelEncoder, ) iris = datasets.load_iris(…

sklearn にて、適合率と再現率

以下の投稿で load したX_train, y_train,... を利用。 kidnohr.hatenadiary.com 適合率と再現率と F1 スコア 適合率(PRE)と再現率(REC)について、F1 スコアという性能指標が存在する。 PRE = TP / ( TP + FP ) REC = TP / ( TP + FN ) f1 = 2 * ( PRE *…

グリッドサーチを使ったチューニング

サポートベクトルマシンのパイプラインのトレーニング from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.model_selection import GridSearchCV …

sklearnのpipelineの使い方

make_pipelineを通して、(入力)=>(変換器(複数))=>(推定器)=>(出力) のwrapperを利用できる。 変換器は fit & transform 推定器は fit import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.preprocessing import Label…

ランダムフォレストで特徴選択する方法

次元削減で特徴抽出する方法を本から抜粋 df_wine = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None) from sklearn.ensemble import RandomForestClassifier feat_labels = df_wine.columns[1:] fore…

二次元の分類結果を plot

機械学習の結果、2 個の特徴の座標と分類結果をわかりやすく図で出力している import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def plot_dicision_regions(X, y, classifier, test_idx=None, resolusions…

.tgz のファイルを開いて読み取る方法

tarfile はZipとは違うアプローチが必要 import tarfile workpath = '/tmp/test.tgz' filename = 'test1.tsv' with tarfile.open(workpath) as tfile: if filename not in tfile.getnames(): raise Exception('No such file %s' % filename) with tfile.extr…

LDA(Latent Dirichlet Allocation) でのトピック抽出

以下の形式のsample.csvからデータを取得し、sklean の LDA でトピック抽出する。 id text 1 今日は晴れ。明日は雨 2 今日はカープが優勝した。 ... ... text2topic.py #!/usr/bin/env python # coding:utf-8 from __future__ import print_function from ti…

SolrのTermVectorsComponentでキーワード抽出してみる

tfidfを用いてなにかできないかと模索。 結果、検索で引っかかつキーワードが出てきただけ。。 The Term Vector Component | Apache Solr Reference Guide 7.1 #!/usr/bin/env python # coding:utf-8 import requests import json from heapq import heappus…

djangoのtest(django-nose, coverage)を使用する時

djangoでtestをするとき、django-nose、coverageが使える。 $ pip install nose $ pip install django-nose $ pip install coverage settigns.py INSTALLED_APPS += ['django_nose', ] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--wi…

1億行のファイルを読み込む方法

ファイルを書き出す manyrowstsv.py #!/usr/bin/env python # coding:utf-8 import signal import sys import os import glob import logging import logging.handlers import shutil import tempfile import random import datetime import string import c…

最大流について

問題 s => t に最大量のデータを流す場合、最大どれだけのデータを送信できるか。 class MaxTraffic(object): def __init__(self, N=5): self.N = N self.edge = [[] for i in range(N)] self.used = [0 for i in range(N)] self.inf = 10 ** 9 def append(s…

最小値の最大化(二分探索)と、反転操作回数の最小化

面白い問題があったのでPythonで記載。 問題 1 N個の牛小屋について、M頭の牛を買っている。 x・・・牛小屋の位置 最も近い牛の間隔を最大化するためにどうするか 解法 最小・最大化問題について、収束判定するために二分探索が用いられるらしい --> 総当た…

Numpyのnewaxisの説明で分かりやすいのがあった

stackoverflow.com

レーベンシュタイン距離をいい感じにまとめているサイトがあった

いまさら編集距離 (Levenshtein Distance) を実装するぜ | takuti.me

最小全域木問題について(プリム法)

class MinimumSpanningTree(object): def __init__(self, v): self.v = v self.e = 0 self.mincost = [float("inf") for i in range(v)] self.cost = [[float("inf") for i in range(v)] for i in range(v)] self.used = [0 for i in range(v)] def append(s…