当前位置:网站首页>Machine learning Basics - decision tree-12
Machine learning Basics - decision tree-12
2022-07-28 12:56:00 【gemoumou】
Decision tree Decision Tree












Decision tree - Example
from sklearn.feature_extraction import DictVectorizer
from sklearn import tree
from sklearn import preprocessing
import csv
# Read in the data
Dtree = open(r'AllElectronics.csv', 'r')
reader = csv.reader(Dtree)
# Get the first row of data
headers = reader.__next__()
print(headers)
# Define two lists
featureList = []
labelList = []
#
for row in reader:
# hold label Deposit in list
labelList.append(row[-1])
rowDict = {
}
for i in range(1, len(row)-1):
# Build a data dictionary
rowDict[headers[i]] = row[i]
# Store the data dictionary in list
featureList.append(rowDict)
print(featureList)

# Convert data into 01 Express
vec = DictVectorizer()
x_data = vec.fit_transform(featureList).toarray()
print("x_data: " + str(x_data))
# Print attribute name
print(vec.get_feature_names())
# Print labels
print("labelList: " + str(labelList))
# Convert labels into 01 Express
lb = preprocessing.LabelBinarizer()
y_data = lb.fit_transform(labelList)
print("y_data: " + str(y_data))

# Create a decision tree model
model = tree.DecisionTreeClassifier(criterion='entropy')
# Input data to build model
model.fit(x_data, y_data)

# test
x_test = x_data[0]
print("x_test: " + str(x_test))
predict = model.predict(x_test.reshape(1,-1))
print("predict: " + str(predict))












Decision tree -CART
from sklearn import tree
import numpy as np
# Load data
data = np.genfromtxt("cart.csv", delimiter=",")
x_data = data[1:,1:-1]
y_data = data[1:,-1]
# Create a decision tree model
model = tree.DecisionTreeClassifier()
# Input data to build model
model.fit(x_data, y_data)

# Export decision tree
import graphviz # http://www.graphviz.org/
dot_data = tree.export_graphviz(model,
out_file = None,
feature_names = ['house_yes','house_no','single','married','divorced','income'],
class_names = ['no','yes'],
filled = True,
rounded = True,
special_characters = True)
graph = graphviz.Source(dot_data)
graph.render('cart')


Decision tree - Linear dichotomy
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report
from sklearn import tree
# Load data
data = np.genfromtxt("LR-testSet.csv", delimiter=",")
x_data = data[:,:-1]
y_data = data[:,-1]
plt.scatter(x_data[:,0],x_data[:,1],c=y_data)
plt.show()

# Create a decision tree model
model = tree.DecisionTreeClassifier()
# Input data to build model
model.fit(x_data, y_data)

# Export decision tree
import graphviz # http://www.graphviz.org/
dot_data = tree.export_graphviz(model,
out_file = None,
feature_names = ['x','y'],
class_names = ['label0','label1'],
filled = True,
rounded = True,
special_characters = True)
graph = graphviz.Source(dot_data)

# Get the range of data values
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# Generate grid matrix
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])# ravel And flatten similar , Multidimensional data to one dimension .flatten Will not change the original data ,ravel Will change the original data
z = z.reshape(xx.shape)
# Contour map
cs = plt.contourf(xx, yy, z)
# Sample scatter plot
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()

predictions = model.predict(x_data)
print(classification_report(predictions,y_data))

Decision tree - Nonlinear dichotomy
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report
from sklearn import tree
from sklearn.model_selection import train_test_split
# Load data
data = np.genfromtxt("LR-testSet2.txt", delimiter=",")
x_data = data[:,:-1]
y_data = data[:,-1]
plt.scatter(x_data[:,0],x_data[:,1],c=y_data)
plt.show()

# Split data
x_train,x_test,y_train,y_test = train_test_split(x_data, y_data)
# Create a decision tree model
# max_depth, Depth of tree
# min_samples_split Minimum number of samples required for internal node subdivision
model = tree.DecisionTreeClassifier(max_depth=7,min_samples_split=4)
# Input data to build model
model.fit(x_train, y_train)

# Export decision tree
import graphviz # http://www.graphviz.org/
dot_data = tree.export_graphviz(model,
out_file = None,
feature_names = ['x','y'],
class_names = ['label0','label1'],
filled = True,
rounded = True,
special_characters = True)
graph = graphviz.Source(dot_data)

# Get the range of data values
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# Generate grid matrix
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])# ravel And flatten similar , Multidimensional data to one dimension .flatten Will not change the original data ,ravel Will change the original data
z = z.reshape(xx.shape)
# Contour map
cs = plt.contourf(xx, yy, z)
# Sample scatter plot
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()

predictions = model.predict(x_train)
print(classification_report(predictions,y_train))

predictions = model.predict(x_test)
print(classification_report(predictions,y_test))


Back to the tree
import numpy as np
import matplotlib.pyplot as plt
from sklearn import tree
# Load data
data = np.genfromtxt("data.csv", delimiter=",")
x_data = data[:,0,np.newaxis]
y_data = data[:,1,np.newaxis]
plt.scatter(x_data,y_data)
plt.show()

model = tree.DecisionTreeRegressor(max_depth=5)
model.fit(x_data, y_data)

x_test = np.linspace(20,80,100)
x_test = x_test[:,np.newaxis]
# drawing
plt.plot(x_data, y_data, 'b.')
plt.plot(x_test, model.predict(x_test), 'r')
plt.show()

# Export decision tree
import graphviz # http://www.graphviz.org/
dot_data = tree.export_graphviz(model,
out_file = None,
feature_names = ['x','y'],
class_names = ['label0','label1'],
filled = True,
rounded = True,
special_characters = True)
graph = graphviz.Source(dot_data)

Back to the tree - Forecast house prices
from sklearn import tree
from sklearn.datasets.california_housing import fetch_california_housing
from sklearn.model_selection import train_test_split
housing = fetch_california_housing()
print(housing.DESCR)

housing.data.shape

housing.data[0]

housing.target[0]

x_data = housing.data
y_data = housing.target
x_train,x_test,y_train,y_test = train_test_split(x_data, y_data)
model = tree.DecisionTreeRegressor()
model.fit(x_train, y_train)


边栏推荐
- 十三. 实战——常用依赖的作用
- 单调栈Monotonic Stack
- VS code更新后不在原来位置
- STM32F103 几个特殊引脚做普通io使用注意事项以及备份寄存器丢失数据问题1,2
- How to add PDF virtual printer in win11
- Uncover why devaxpress WinForms, an interface control, discards the popular maskbox property
- Machine learning practice - neural network-21
- Flexpro software: measurement data analysis in production, research and development
- BA autoboot plug-in of uniapp application boot
- Hc-05 Bluetooth module debugging slave mode and master mode experience
猜你喜欢

Fundamentals of machine learning - support vector machine svm-17

机器学习实战-决策树-22

Leetcode 42. rainwater connection

leetcode 1518. 换酒问题

scala 转换、过滤、分组、排序

SuperMap iclient3d for webgl to realize floating thermal map

Cloud native - runtime environment

Introduction to border border attribute

LeetCode84 柱状图中最大的矩形

揭秘界面控件DevExpress WinForms为何弃用受关注的MaskBox属性
随机推荐
机器学习实战-集成学习-23
Brief introduction to JS operator
AVL tree (balanced search tree)
Detailed explanation of the usage of C # static
leetcode 1518. 换酒问题
MSP430 开发中遇到的坑(待续)
Fundamentals of machine learning - support vector machine svm-17
05 pyechars 基本图表(示例代码+效果图)
[basic teaching of Bi design] detailed explanation of OLED screen use - single chip microcomputer Internet of things
Leetcode394 string decoding
大模型哪家强?OpenBMB发布BMList给你答案!
机器学习基础-贝叶斯分析-14
01 introduction to pyechars features, version and installation
04 pyechars 地理图表(示例代码+效果图)
Installation and reinstallation of win11 system graphic version tutorial
STM32F103 几个特殊引脚做普通io使用注意事项以及备份寄存器丢失数据问题1,2
Hc-05 Bluetooth module debugging slave mode and master mode experience
LeetCode84 柱状图中最大的矩形
FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be depreca
STM32 loopback structure receives and processes serial port data