经典机器学习代码
时间: 2023-06-21 19:05:51 浏览: 96
以下是一些经典的机器学习代码:
1. 线性回归
```python
import numpy as np
from sklearn.linear_model import LinearRegression
# create data
X = np.array([[1, 1], [2, 2.5], [3, 1.2], [4, 3.1], [5, 2]])
y = np.array([5, 12, 7, 15, 11])
# create linear regression model
lr = LinearRegression()
# fit the model to the data
lr.fit(X, y)
# predict new values
X_new = np.array([[6, 1.5], [7, 2]])
y_pred = lr.predict(X_new)
print(y_pred)
```
2. K均值聚类
```python
import numpy as np
from sklearn.cluster import KMeans
# create data
X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
# create k-means model
kmeans = KMeans(n_clusters=2)
# fit the model to the data
kmeans.fit(X)
# predict new values
X_new = np.array([[2, 3], [6, 6]])
y_pred = kmeans.predict(X_new)
print(y_pred)
```
3. 支持向量机
```python
import numpy as np
from sklearn.svm import SVC
# create data
X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
y = np.array([0, 0, 1, 1, 0, 1])
# create SVM model
svm = SVC(kernel='linear')
# fit the model to the data
svm.fit(X, y)
# predict new values
X_new = np.array([[2, 3], [6, 6]])
y_pred = svm.predict(X_new)
print(y_pred)
```
这些代码都是使用 Scikit-learn 库实现的。你可以在 Scikit-learn 的官方文档中找到更多的例子和详细的解释。
阅读全文