常见的建模方法及python语言模型实现代码
时间: 2024-01-02 11:03:46 浏览: 32
常见的建模方法包括线性回归、逻辑回归、决策树、随机森林、支持向量机、朴素贝叶斯、神经网络等。下面是对应的Python语言模型实现代码:
1. 线性回归:
```python
from sklearn.linear_model import LinearRegression
# 构建数据集
X = [[0], [1], [2], [3]]
y = [0, 1, 2, 3]
# 定义线性回归模型
model = LinearRegression()
# 训练模型
model.fit(X, y)
# 预测
y_pred = model.predict([[4]])
print(y_pred)
```
2. 逻辑回归:
```python
from sklearn.linear_model import LogisticRegression
# 构建数据集
X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
# 定义逻辑回归模型
model = LogisticRegression()
# 训练模型
model.fit(X, y)
# 预测
y_pred = model.predict([[4]])
print(y_pred)
```
3. 决策树:
```python
from sklearn.tree import DecisionTreeClassifier
# 构建数据集
X = [[0, 0], [0, 1], [1, 0], [1, 1]]
y = [0, 1, 1, 0]
# 定义决策树模型
model = DecisionTreeClassifier()
# 训练模型
model.fit(X, y)
# 预测
y_pred = model.predict([[0, 0], [0, 1], [1, 0], [1, 1]])
print(y_pred)
```
4. 随机森林:
```python
from sklearn.ensemble import RandomForestClassifier
# 构建数据集
X = [[0, 0], [0, 1], [1, 0], [1, 1]]
y = [0, 1, 1, 0]
# 定义随机森林模型
model = RandomForestClassifier()
# 训练模型
model.fit(X, y)
# 预测
y_pred = model.predict([[0, 0], [0, 1], [1, 0], [1, 1]])
print(y_pred)
```
5. 支持向量机:
```python
from sklearn.svm import SVC
# 构建数据集
X = [[0], [1], [2], [3]]
y = [0, 1, 2, 3]
# 定义支持向量机模型
model = SVC()
# 训练模型
model.fit(X, y)
# 预测
y_pred = model.predict([[4]])
print(y_pred)
```
6. 朴素贝叶斯:
```python
from sklearn.naive_bayes import GaussianNB
# 构建数据集
X = [[0, 0], [0, 1], [1, 0], [1, 1]]
y = [0, 1, 1, 0]
# 定义朴素贝叶斯模型
model = GaussianNB()
# 训练模型
model.fit(X, y)
# 预测
y_pred = model.predict([[0, 0], [0, 1], [1, 0], [1, 1]])
print(y_pred)
```
7. 神经网络:
```python
from keras.models import Sequential
from keras.layers import Dense
# 构建数据集
X = [[0], [1], [2], [3]]
y = [0, 1, 2, 3]
# 定义神经网络模型
model = Sequential()
model.add(Dense(units=10, input_dim=1, activation='relu'))
model.add(Dense(units=1, activation='linear'))
# 编译模型
model.compile(loss='mse', optimizer='adam')
# 训练模型
model.fit(X, y, epochs=1000, verbose=0)
# 预测
y_pred = model.predict([[4]])
print(y_pred)
```