import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
nba = pd.read_csv("D:\\test\\machineLearning\\nba_2013.csv")
print nba.head(3)
player pos age bref_team_id g gs mp fg fga fg. \ 0 Quincy Acy SF 23 TOT 63 0 847 66 141 0.468 1 Steven Adams C 20 OKC 81 20 1197 93 185 0.503 2 Jeff Adrien PF 27 TOT 53 12 961 143 275 0.520 … drb trb ast stl blk tov pf pts season season_end 0 … 144 216 28 23 26 30 122 171 2013-2014 2013 1 … 190 332 43 40 57 71 203 265 2013-2014 2013 2 … 204 306 38 24 36 39 108 362 2013-2014 2013 [3 rows x 31 columns]
point_guards = nba[nba["pos"]=="PG"]
point_guards["ppg"] = point_guards['pts']/point_guards['g']
point_guards[['pts','g','ppg']].head(5)
C:\Users\qiujiahao\Anaconda2\lib\site-packages\ipykernel\__main__.py:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
|
pts |
g |
ppg |
24 |
930 |
71 |
13.098592 |
29 |
150 |
20 |
7.500000 |
30 |
660 |
79 |
8.354430 |
38 |
666 |
72 |
9.250000 |
50 |
378 |
55 |
6.872727 |
point_guards=point_guards[point_guards['tov']!=0]
point_guards['atr'] = point_guards['ast']/point_guards['tov']
plt.scatter(point_guards['ppg'],point_guards['atr'],c='y')
plt.title("Point Guards")
plt.xlabel("Points Per Game",fontsize=13)
plt.ylabel("Assist Turnover Ratio",fontsize=13)
plt.show()
num_clusters=5
random_initial_points=np.random.choice(point_guards.index,size=num_clusters)
centroids = point_guards.loc[random_initial_points]
plt.scatter(point_guards['ppg'],point_guards['atr'],c='yellow')
plt.scatter(centroids['ppg'],centroids['atr'],c='red')
plt.title("Centroids")
plt.xlabel('Points Per Game',fontsize=13)
plt.ylabel('Assist Turnover Ratio',fontsize=13)
plt.show()
def centroids_to_dict(centroids):
dictionary = dict()
counter = 0
for index,row in centroids.iterrows():
coordinates = [row['ppg'],row['atr']]
dictionary[counter]=coordinates
counter += 1
return dictionary
centroids_dict = centroids_to_dict(centroids)
print centroids_dict
{0: [7.5, 1.6842105263157894], 1: [17.936708860759495, 3.020618556701031], 2: [9.5, 2.43609022556391], 3: [1.125, 2.5555555555555554], 4: [1.0, 3.4]}
def calculate_distance(centroid,player_values):
root_distance=0
for x in range(0,len(centroid)):
difference = centroid[x]-player_values[x]
squared_difference = difference**2
root_distance += squared_difference
euclid_distance = math.sqrt(root_distance)
return euclid_distance
q = [5,2]
p = [3,1]
print (calculate_distance(q,p))
2.2360679775
def assign_to_cluster(row):
lowest_distance=-1
closest_cluster=-1
euclidean_distance=-1
for cluster_id,centroid in centroids_dict.items():
df_row = [row['ppg'],row['atr']]
euclidean_distance = calculate_distance(centroid,df_row)
if lowest_distance == -1:
lowest_distance = euclidean_distance
closest_cluster = cluster_id
elif euclidean_distance < lowest_distance:
lowest_distance = euclidean_distance
closest_cluster = cluster_id
return closest_cluster
point_guards['cluster'] = point_guards.apply(lambda row:assign_to_cluster(row),axis=1)
def visualize_clusters(df,num_clusters):
colors = ['b','g','r','c','m','y','k']
for n in range(num_clusters):
clustered_df = df[df['cluster'] == n]
plt.scatter(clustered_df['ppg'],clustered_df['atr'],c=colors[n-1])
plt.xlabel('Points Per Game',fontsize=13)
plt.ylabel('Assist Turnover Ratio',fontsize=13)
plt.show()
visualize_clusters(point_guards,5)
def recalculate_centroids(df):
new_centroids_dict = dict()
for cluster_id in range(0,num_clusters):
class_all=df[df['cluster']==cluster_id]
mean_ppg = class_all['ppg'].mean()
mean_atr = class_all['atr'].mean()
new_centroids_dict[cluster_id]= [mean_ppg,mean_atr]
return new_centroids_dict
centroids_dict = recalculate_centroids(point_guards)
point_guards["cluster"] = point_guards.apply(lambda row:assign_to_cluster(row),axis=1)
visualize_clusters(point_guards,5)
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=num_clusters)
kmeans.fit(point_guards[['ppg','atr']])
point_guards['cluster'] = kmeans.labels_
visualize_clusters(point_guards,num_clusters)