我试图使用树分类器创建一个简单的疾病症状分类。我已经尝试使用sklearn的树分类器,但出现了以下错误。我的代码和错误都在这里。有什么建议吗?
import numpy as npfrom sklearn import treesymptoms = [['flat face','poor moro','hypotonia'],['small head','small jaw','overlapping fingers'], ['small eyes','cleft lip','cleft palate']]lables = [['Trisomy 21'],['Trisomy 18'],['Trisomy 13']]classify = tree.DecisionTreeClassifier()classify = classify.fit(symptoms, lables)
它给出了以下错误
ValueError Traceback (most recent call last)<ipython-input-25-0f2c956618c2> in <module> 4 lables = [['Trisomy 21'],['Trisomy 18'],['Trisomy 13']] 5 classify = tree.DecisionTreeClassifier()----> 6 classify = classify.fit(symptoms, lables)c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted) 799 sample_weight=sample_weight, 800 check_input=check_input,--> 801 X_idx_sorted=X_idx_sorted) 802 return self 803 c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted) 114 random_state = check_random_state(self.random_state) 115 if check_input:--> 116 X = check_array(X, dtype=DTYPE, accept_sparse="csc") 117 y = check_array(y, ensure_2d=False, dtype=None) 118 if issparse(X):c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 525 try: 526 warnings.simplefilter('error', ComplexWarning)--> 527 array = np.asarray(array, dtype=dtype, order=order) 528 except ComplexWarning: 529 raise ValueError("Complex data not supported\n"c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\numpy\core\numeric.py in asarray(a, dtype, order) 499 500 """--> 501 return array(a, dtype, copy=False, order=order) 502 503 ValueError: could not convert string to float: 'flat face'
回答:
你需要使用label encoder
来编码你的字符串值。以下代码可以满足你的需求:
import numpy as npfrom sklearn import treefrom sklearn.preprocessing import LabelEncodersymptoms = [['flat face','poor moro','hypotonia'],['small head','small jaw','overlapping fingers'], ['small eyes','cleft lip','cleft palate']]lables = [['Trisomy 21'],['Trisomy 18'],['Trisomy 13']]df = pd.concat([pd.DataFrame(symptoms), pd.DataFrame(lables)], axis=1)x_cols = ['sym1', 'sym2', 'sym3']y_col = 'target'df.columns = x_cols + [y_col]df = df.apply(LabelEncoder().fit_transform)classify = tree.DecisionTreeClassifier()classify.fit(df[x_cols].values, df[y_col].values)