from sklearn import datasets
import matplotlib.pyplot as plt
# Load the iris dataset
iris=datasets.load_iris()
import dtreeviz
# we only take the first two features (sepal length and sepal width)
X=iris.data[:,:2]
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=iris.target, cmap=plt.cm.Set1, edgecolor='k')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.title('Sepal Length vs Sepal Width')
plt.show()
fig, axarr = plt.subplots(4, 4, figsize=(15, 15))
plt.subplots_adjust(wspace=0.4, hspace=0.4)
features = iris.feature_names
for i in range(4):
for j in range(4):
if i == j:
axarr[i, j].text(0.5, 0.5, features[i], fontsize=12, ha='center')
axarr[i, j].axis('off')
else:
axarr[i, j].scatter(iris.data[:, j], iris.data[:, i], c=iris.target, cmap=plt.cm.Set1, edgecolor='k', s=20)
if i == 3:
axarr[i, j].set_xlabel(features[j])
if j == 0:
axarr[i, j].set_ylabel(features[i])
# show the plot
plt.show()
def classify_iris(sample):
if sample[2] <= 2.45:
return 0
elif sample[2] > 2.45 and sample[3] <= 1.75:
if sample[1] <= 2.8:
return 1
else:
return 2
else:
if sample[0] <= 6.05:
return 1
else:
return 2
# import train_test_split
from sklearn.model_selection import train_test_split
# Split the data into training and testing sets
X_train,X_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=.3,random_state=42)
classify_iris(X_test[0])
from sklearn.metrics import accuracy_score
# Apply the classification function to the test set
y_pred = [classify_iris(sample) for sample in X_test]
# Calculate the accuracy
accuracy = accuracy_score(y_test, y_pred)
accuracy
from sklearn.linear_model import LogisticRegression
# Initialize the model
clf= LogisticRegression()
# Train the model on the training set
clf.fit(X_train,y_train)
# Predict on the test set
y_pred=clf.predict(X_test)
# Calculate the accuracy
acc=accuracy_score(y_test,y_pred)
from sklearn.metrics import accuracy_score
accuracy_score(y_test, y_pred)
from sklearn.tree import DecisionTreeClassifier
# 初始化决策树分类器
clf = DecisionTreeClassifier()
# 在训练集上训练模型
clf.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = clf.predict(X_test)
# 计算准确率
acc = accuracy_score(y_test, y_pred)
target_names=[iris.target_names[0],iris.target_names[1],iris.target_names[2]]
target_names
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
# 可视化决策树
plt.figure(figsize=(20, 10))
plot_tree(clf, filled=True, feature_names = iris.feature_names,
class_names=target_names)
plt.show()
import numpy as np
from dtreeviz import dtreeviz
sample_idx = np.random.randint(0, len(X))
viz=dtreeviz(clf,X_test[sample_idx:sample_idx+1], y_test[sample_idx:sample_idx+1],target_name='species',feature_names = iris.feature_names,class_names=target_names)
viz.view()
![](https://profile-avatar.csdnimg.cn/689fdff7ed9d4cc18c638171392783bf_2301_79738703.jpg!4)
利用iris鸢尾花进行机器学习时,使用dtreeviz生成决策树可视化时,为什么一直报错TypeError:int object is not subscriptable?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- Kwan的解忧杂货铺@新空间代码工作室 2024-03-14 22:03关注
三心九尾狐 晚上好🌙🌙🌙
本答案参考ChatGPT-3.5出现TypeError: int object is not subscriptable错误的原因是在使用dtreeviz生成决策树可视化时,传入的标签值类型为整数,而不支持整数类型的索引。要解决此错误,可以通过将标签值转换为字符串类型来解决。
下面是解决方案:
- 在将标签值传给dtreeviz之前,将其转换为字符串类型。
- 修改生成决策树可视化的代码,使用转换后的标签值。
修改后的代码如下:
import numpy as np from dtreeviz import dtreeviz sample_idx = np.random.randint(0, len(X)) y_test_str = [target_names[i] for i in y_test] # 将标签值转换为字符串类型 viz = dtreeviz(clf, X_test[sample_idx:sample_idx+1], y_test_str[sample_idx:sample_idx+1], target_name='species', feature_names=iris.feature_names, class_names=target_names) viz.view()
通过将标签值转换为字符串类型,可以避免TypeError: int object is not subscriptable错误,并成功生成决策树可视化。
解决 无用评论 打赏 举报
悬赏问题
- ¥15 无法输出helloworld
- ¥15 高通uboot 打印ubi init err 22
- ¥20 PDF元数据中的XMP媒体管理属性
- ¥15 R语言中lasso回归报错
- ¥15 网站突然不能访问了,上午还好好的
- ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
- ¥15 semrush,SEO,内嵌网站,api
- ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
- ¥15 振荡电路,ADS仿真
- ¥15 关于#c语言#的问题,请各位专家解答!