Created
October 13, 2015 14:36
-
-
Save rnowling/cd05281eeafe46b38158 to your computer and use it in GitHub Desktop.
Customer Segmentation Pipeline Prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Copyright 2015 Ronald J. Nowling | |
Licensed under the Apache License, Version 2.0 (the "License"); | |
you may not use this file except in compliance with the License. | |
You may obtain a copy of the License at | |
http://www.apache.org/licenses/LICENSE-2.0 | |
Unless required by applicable law or agreed to in writing, software | |
distributed under the License is distributed on an "AS IS" BASIS, | |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
See the License for the specific language governing permissions and | |
limitations under the License. | |
""" | |
import sys | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import csv | |
from sklearn.decomposition import PCA | |
from sklearn.cluster import k_means | |
from scipy.stats import rankdata | |
from sklearn.feature_extraction.text import TfidfTransformer | |
from sklearn.metrics import confusion_matrix | |
from sklearn.naive_bayes import MultinomialNB | |
def read_matrix(flname): | |
ratings = [] | |
max_user_id = 0 | |
max_item_id = 0 | |
with open(flname) as fl: | |
reader = csv.reader(fl, delimiter="\t") | |
for rec in reader: | |
user_id = int(rec[0]) | |
item_id = int(rec[1]) | |
rating = float(rec[2]) | |
ratings.append((user_id, item_id, rating)) | |
max_user_id = max(max_user_id, user_id) | |
max_item_id = max(max_item_id, item_id) | |
features = np.zeros((max_user_id, max_item_id)) | |
for user_id, item_id, rating in ratings: | |
features[user_id - 1, item_id - 1] = rating | |
return features | |
def read_items(flname): | |
items = [] | |
with open(flname) as fl: | |
reader = csv.reader(fl, delimiter="|") | |
for rec in reader: | |
items.append(rec[1]) | |
return items | |
def plot_explained_var_ratios(dirname, pca): | |
plt.plot(pca.explained_variance_ratio_[:20], "b.-") | |
plt.xlabel("Component", fontsize=16) | |
plt.ylabel("Explained Variance Ratio", fontsize=16) | |
plt.ylim([0.0, 1.0]) | |
plt.savefig(dirname + "/pca_explained_var_ratio.pdf", DPI=200) | |
def plot_clusters(dirname, proj_features, features): | |
plt.clf() | |
plt.hold(True) | |
ks = [5, 10, 25, 50, 100, 125, 150, 200] | |
proj_costs = [] | |
full_costs = [] | |
for k in ks: | |
centroids, labels, inertia = k_means(proj_features, k) | |
proj_costs.append(inertia) | |
centroids, labels, inertia = k_means(features, k) | |
full_costs.append(inertia) | |
plt.plot(ks, np.array(proj_costs) / max(proj_costs), "b.-", label="Projected") | |
plt.plot(ks, np.array(full_costs) / max(full_costs), "r.-", label="Full") | |
plt.legend(loc="upper right") | |
plt.xlabel("Centers", fontsize=16) | |
plt.ylabel("Inertia", fontsize=16) | |
plt.savefig(dirname + "/kmeans_inertia.pdf", DPI=200) | |
def plot_confusion_matrix(dirname, cm, title='Confusion matrix', cmap=plt.cm.Blues): | |
plt.clf() | |
plt.imshow(cm, interpolation='nearest') | |
plt.title(title) | |
plt.colorbar() | |
plt.tight_layout() | |
plt.ylabel('True label') | |
plt.xlabel('Predicted label') | |
plt.savefig(dirname + "/confusion_matrix.pdf", DPI=200) | |
if __name__ == "__main__": | |
movielens_dir = sys.argv[1] | |
data_fl = movielens_dir + "/u.data" | |
items_fl = movielens_dir + "/u.item" | |
outdir = "figures" | |
features = read_matrix(data_fl) | |
print features.shape | |
sparsity = float(np.count_nonzero(features)) / (features.shape[0] | |
* features.shape[1]) | |
print "Sparsity", sparsity | |
pca = PCA() | |
projected = pca.fit_transform(features) | |
plot_explained_var_ratios(outdir, pca) | |
n_pcs = 10 | |
plot_clusters(outdir, projected[:, :n_pcs], features) | |
_, labels, _ = k_means(projected[:, :n_pcs], 25) | |
nb = MultinomialNB() | |
nb.fit(features, labels) | |
predicted = nb.predict(features) | |
cm = confusion_matrix(labels, predicted) | |
plot_confusion_matrix(outdir, cm) | |
scaler = TfidfTransformer() | |
scaled = scaler.fit_transform(features, labels).todense() | |
print scaled.shape | |
items = read_items(items_fl) | |
for i in xrange(25): | |
members = scaled[labels == i, :] | |
print i, members.shape | |
avg_rank = np.mean(members, axis=0) | |
ranks = rankdata(avg_rank) | |
rank_idx = np.argsort(-1.0 * ranks) | |
for j in rank_idx[:10]: | |
print "\t", items[j], avg_rank[0, j] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment