我正在尝试使用python和pandas解析相对较大的.csv(近1.000.000行)文件。更具体地说,我想实现肘方法以为K-Means算法找到合适的'k'值。我的脚本如下
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
data = pd.read_csv('withcountries.csv', sep=',')
data.head()
categorical_features = ['vendor_name', 'ship_from', 'market_name', 'name' ]
continuous_features = ['price']
for col in categorical_features:
dummies = pd.get_dummies(data[col], prefix=col)
data = pd.concat([data, dummies], axis=1)
data.drop(col, axis=1, inplace=True)
mms = MinMaxScaler()
mms.fit(data)
data_transformed = mms.transform(data)
Sum_of_squared_distances = []
K = range(1,15)
for k in K:
km = KMeans(n_clusters=k)
km = km.fit(data_transformed)
Sum_of_squared_distances.append(km.inertia_)
plt.plot(K, Sum_of_squared_distances, 'bx-')
plt.xlabel('k')
plt.ylabel('Sum_of_squared_distances')
plt.title('Elbow Method For Optimal k')
plt.show()
脚本正在运行(已测试nrows=10000
)。我的问题是,当我在本地解析整个文件时,我得到了Memory Error
。因此,我决定在AWS的EC2实例上运行它。我安装了Python3,但是在运行完全相同的脚本时,出现这种错误KeyError: 'market_name'
。
注意:如果我在本地运行脚本,则一切正常,仅在EC2中,我会收到此错误。任何人都知道为什么会这样吗?