import numpy as np import pandas as pd import matplotlib.pyplot as plt from decision_tree_classifier import DecisionTreeClassifier from random_forest_classifier import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score #读取数据 df = pd.read_csv('adult.csv',encoding='gbk') df.head() col_names=['age','workclass','fnlwgt','education','educational-num','marital-status','occupation','relationship','race','gender','capital-gain','capital-loss','hours-per-week','native-country','income'] df.columns = col_names categorical = ['workclass','education','marital-status','occupation','relationship','race','gender','native-country','income'] # print(f'分类特征:\n{categorical}') # for var in categorical: # print(df[var].value_counts()) #缺失值处理 df['occupation'].replace('?', np.NaN, inplace=True) df['workclass'].replace('?', np.NaN, inplace=True) df['native-country'].replace('?', np.NaN, inplace=True) df.isnull().sum() df['income'].value_counts() plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] df.isnull().sum() df['workclass'].fillna(df['workclass'].mode()[0], inplace=True) df['occupation'].fillna(df['occupation'].mode()[0], inplace=True) df['native-country'].fillna(df['native-country'].mode()[0], inplace=True) df = pd.get_dummies(df,columns=categorical,drop_first=True) print(df.head()) y = df.loc[:,'income_>50K'] X = np.array(df.loc[:,['age', 'educational-num', 'hours-per-week']]) y = np.array(y) x = np.array(X) y = y.reshape(-1,1) X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=1234) from sklearn.ensemble import RandomForestClassifier rtree = RandomForestClassifier(n_estimators=100,max_depth=5,max_features=0.2,max_samples=50,random_state=1234) X_train = np.array(X_train) rtree.fit(X_train, y_train) X_test = np.array(X_test) y_pred = rtree.predict(X_test) accuracy = accuracy_score(y_test,y_pred) print("accuracy={}".format((accuracy)))我这个代码如何更换特征向量
时间: 2023-08-04 07:08:11 浏览: 202
Matplotlib.pyplot 三维绘图的实现示例
如果想更换特征向量,只需要修改以下代码段:
```
X = np.array(df.loc[:,['age', 'educational-num', 'hours-per-week']])
y = np.array(y)
```
将 `['age', 'educational-num', 'hours-per-week']` 替换为你想要的特征向量即可。注意要保证特征向量的格式正确,即为一个列表形式。另外,如果更换特征向量后发现模型表现不佳,可以再考虑增加或减少特征,或者对特征进行预处理等操作。
阅读全文