Python代码怎么建立模型?

文章导读
使用sklearn库快速建立一个简单模型:from sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitimport numpy as npX = np.random.rand(100,1)*10y = 2.5*X.ravel() + np.random.ra
📋 目录
  1. A 方法一:使用Keras建立神经网络模型
  2. B 方法二:PyTorch建立模型
  3. C 方法三:Scikit-learn分类模型
  4. D TensorFlow简单模型
  5. E XGBoost模型建立
  6. F LightGBM快速建模
A A

使用sklearn库快速建立一个简单模型:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
X = np.random.rand(100,1)*10
y = 2.5*X.ravel() + np.random.rand(100)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LinearRegression()
model.fit(X_train, y_train)
print(model.score(X_test, y_test))

方法一:使用Keras建立神经网络模型

from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=32)

方法二:PyTorch建立模型

import torch
import torch.nn as nn
import torch.optim as optim
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(28*28, 200)
self.fc2 = nn.Linear(200, 10)
def forward(self, x):
x = x.view(-1, 28*28)
h = torch.tanh(self.fc1(x))
h = self.fc2(h)
return h

Python代码怎么建立模型?

方法三:Scikit-learn分类模型

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
iris = datasets.load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=0)
model = RandomForestClassifier(n_estimators=10)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))

TensorFlow简单模型

import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam',
loss='mse',
metrics=['mae'])
# model.fit(x_train, y_train, epochs=10)

XGBoost模型建立

import xgboost as xgb
dtrain = xgb.DMatrix(X_train, label=y_train)
param = {'max_depth':2, 'eta':1, 'objective':'binary:logistic'}
model = xgb.train(param, dtrain, num_boost_round=10)
dtest = xgb.DMatrix(X_test)
pred = model.predict(dtest)

Python代码怎么建立模型?

LightGBM快速建模

import lightgbm as lgb
train_data = lgb.Dataset(X_train, label=y_train)
params = {'objective': 'regression', 'metric': 'rmse'}
model = lgb.train(params, train_data, num_boost_round=100)
y_pred = model.predict(X_test)

FAQ
Q: 建立模型需要哪些基本步骤?
A: 数据准备→模型选择→训练→评估→预测。
Q: 怎么选择合适的模型?
A: 根据问题类型(分类/回归),从小模型开始尝试。
Q: 模型训练慢怎么办?
A: 减少数据量、使用GPU、简化模型结构。
Q: 怎么保存训练好的模型?
A: sklearn用joblib.dump,Keras用model.save()。