해결된 질문
작성
·
243
0
import pandas as pd
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
cols = train.select_dtypes(include = 'object').columns
from sklearn.preprocessing import LabelEncoder
for col in cols:
le = LabelEncoder()
train[col] = le.fit_transform(train[col])
test[col] = le.transform(test[col])
from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(train.drop('Segmentation', axis=1), train['Segmentation'], test_size=0.1, random_state=2022)
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier()
rf.fit(X_tr, y_tr)
pred = rf.predict(test)
submit=pd.DataFrame({'ID':test["ID"],'Segmentation':pred}).to_csv("003000000.csv", index=False)
import pandas as pd
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
n_train = train.select_dtypes(exclude = "object").copy()
c_train = train.select_dtypes(include='object').copy()
n_test = test.select_dtypes(exclude = "object").copy()
c_test = test.select_dtypes(include='object').copy()
cols1 = ['Age', 'Work_Experience','Family_Size']
from sklearn.preprocessing import RobustScaler
rs = RobustScaler()
n_train[cols1] = rs.fit_transform(n_train[cols1])
n_test[cols1] = rs.transform(n_test[cols1])
cols2 = ['Gender','Ever_Married','Graduated','Profession', 'Spending_Score',
'Var_1']
# 라벨 인코딩
from sklearn.preprocessing import LabelEncoder
for col in cols2:
le = LabelEncoder()
c_train[col] = le.fit_transform(c_train[col])
c_test[col] = le.transform(c_test[col])
# 원핫 인코딩
# c_train = pd.get_dummies(c_train, columns = cols2)
# c_test = pd.get_dummies(c_test, columns = cols2)
# train = pd.concat([n_train, c_train], axis=1)
# test = pd.concat([n_test, c_test], axis=1)
# from sklearn.model_selection import train_test_split
# X_tr, X_val, y_tr, y_val = train_test_split(train.drop('Segmentation', axis=1), train['Segmentation'], test_size=0.1, random_state=2022)
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier()
rf.fit(X_tr, y_tr)
pred = rf.predict(test)
submit=pd.DataFrame({'ID':test["ID"],'Segmentation':pred}).to_csv("002000000.csv", index=False)