Skip to content

Instantly share code, notes, and snippets.

@tonghuikang
Created March 25, 2020 04:47
Show Gist options
  • Save tonghuikang/c57a4f2f05a1a59bf5a148e12ee8b1c3 to your computer and use it in GitHub Desktop.
Save tonghuikang/c57a4f2f05a1a59bf5a148e12ee8b1c3 to your computer and use it in GitHub Desktop.
SML homework template Q3
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"# Q1\n",
"\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from numpy import linalg as LA\n",
"from matplotlib.patches import Ellipse\n",
"from sklearn.datasets.samples_generator import make_blobs \n",
"from scipy.stats import multivariate_normal\n",
"\n",
"K = 3\n",
"NUMDATAPTS = 150\n",
"\n",
"X, y = make_blobs(n_samples=NUMDATAPTS, centers=K, shuffle=False, random_state=0, cluster_std=0.6)\n",
"\n",
"g1 = np.asarray([[2.0, 0], [-0.9, 1]])\n",
"g2 = np.asarray([[1.4, 0], [0.5, 0.7]])\n",
"\n",
"mean1 = np.mean(X[:int(NUMDATAPTS/K)])\n",
"mean2 = np.mean(X[int(NUMDATAPTS/K):2*int(NUMDATAPTS/K)])\n",
"\n",
"X[:int(NUMDATAPTS/K)] = np.einsum('nj,ij->ni', X[:int(NUMDATAPTS/K)] - mean1, g1) + mean1\n",
"X[int(NUMDATAPTS/K):2*int(NUMDATAPTS/K)] = np.einsum('nj,ij->ni', X[int(NUMDATAPTS/K):2*int(NUMDATAPTS/K)] - mean2, g2) + mean2\n",
"X[:,1] -= 4\n",
"\n",
"\n",
"def E_step():\n",
" gamma = np.zeros((NUMDATAPTS, K))\n",
" # your steps here\n",
" return gamma\n",
"\n",
"def M_step(gamma): \n",
" # your steps here\n",
" return None\n",
"\n",
"\n",
"def plot_result(gamma=None):\n",
" ax = plt.subplot (111 , aspect='equal')\n",
" ax.set_xlim([-5, 5])\n",
" ax.set_ylim([-5, 5])\n",
" ax.scatter(X[:, 0], X[:, 1], c=gamma, s=50, cmap=None)\n",
" for k in range(K):\n",
" l, v = LA.eig(cov[k])\n",
" theta = np.arctan(v[1,0]/v[0,0])\n",
" e = Ellipse((mu[k, 0], mu[k, 1]), 6*l[0], 6*l[1], theta*180 / np.pi)\n",
" e.set_alpha(0.5) \n",
" ax.add_artist(e)\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"## Q4\n",
"\n",
"import numpy as np\n",
"from sklearn import decomposition\n",
"from sklearn import datasets\n",
"X = datasets.load_diabetes().data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.7"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment