【python】机器学习相关库下载(萌新向)

本文未加说明都是在命令行中进行操作,且默认成功安装了vscode,安装步骤具体看其他博主写的

首先要更新pip

快捷键windows+R,输入cmd,打开命令行窗口,再输入以下代码:成功的话会显示安装成功的英文。

python -m pip install --upgrade pip

下载wheel

pip3 install wheel

wheel用来安装后续的.whl文件,成功的话会显示安装成功的英文

查看python版本

输入以下代码

python

如果跳出应用商店,则输入以下代码:

py

结果如图所示

根据python版本去下载对应的numpy、scipy和matplotlib库

https://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

在这个网址里找,比如我的python是3.11.2版本,那么这些库的版本应该格式如下(自己找规律)

注意别看错了

下载完之后,点击浏览器的下载/下载内容,点击在文件夹中显示(一般为一个文件夹的形状)

在这个地方删掉所有的东西,输入cmd,回车

出现命令行窗口

输入,按回车,注意不要输错了,他会自己安装的,显示安装成功的英文(三个文件都要安装)

pip install 文件名

 最后安装sklearn

输入:

pip install -U scikit-learn

装完了,做得好!

在vscode创个文件,运行下这个

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 设置随机种子
seed_value = 2023
np.random.seed(seed_value)

# Sigmoid激活函数
def sigmoid(z):
    return 1 / (1 + np.exp(-z))

# 定义逻辑回归算法
class LogisticRegression:
    def __init__(self, learning_rate=0.003, iterations=100):
        self.learning_rate = learning_rate # 学习率
        self.iterations = iterations # 迭代次数

    def fit(self, X, y):
        # 初始化参数
        self.weights = np.random.randn(X.shape[1])
        self.bias = 0

        # 梯度下降
        for i in range(self.iterations):
            # 计算sigmoid函数的预测值, y_hat = w * x + b
            y_hat = sigmoid(np.dot(X, self.weights) + self.bias)

            # 计算损失函数
            loss = (-1 / len(X)) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))

            # 计算梯度
            dw = (1 / len(X)) * np.dot(X.T, (y_hat - y))
            db = (1 / len(X)) * np.sum(y_hat - y)

            # 更新参数
            self.weights -= self.learning_rate * dw
            self.bias -= self.learning_rate * db

            # 打印损失函数值
            if i % 10 == 0:
                print(f"Loss after iteration {i}: {loss}")

    # 预测
    def predict(self, X):
        y_hat = sigmoid(np.dot(X, self.weights) + self.bias)
        y_hat[y_hat >= 0.5] = 1
        y_hat[y_hat < 0.5] = 0
        return y_hat
    
    # 精度
    def score(self, y_pred, y):
        accuracy = (y_pred == y).sum() / len(y)
        return accuracy

# 导入数据
iris = load_iris()
X = iris.data[:, :2]
y = (iris.target != 0) * 1

# 划分训练集、测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=seed_value)

# 训练模型
model = LogisticRegression(learning_rate=0.03, iterations=1000)
model.fit(X_train, y_train)

# 结果
y_train_pred = model.predict(X_train)
y_test_pred = model.predict(X_test)

score_train = model.score(y_train_pred, y_train)
score_test = model.score(y_test_pred, y_test)

print('训练集Accuracy: ', score_train)
print('测试集Accuracy: ', score_test)

# 可视化决策边界
x1_min, x1_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
x2_min, x2_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max, 100), np.linspace(x2_min, x2_max, 100))
Z = model.predict(np.c_[xx1.ravel(), xx2.ravel()])
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, cmap=plt.cm.Spectral)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)
plt.xlabel("Sepal length")
plt.ylabel("Sepal width")
plt.show()

没出错就不管了,如果报错,而且是numpy.core.multiarray failed to import,和API版本是0x10,而numpy版本是0x啥之类的,是numpy和scipy不兼容的问题,就再打开命令行窗口对numpy和scipy进行更新,输入以下代码:

pip install --upgrade numpy
pip install --upgrade scipy

再运行上述程序就没有问题了

如果还报错,可能是opencv-python这个文件版本不兼容,和安装numpy的步骤一样,去https://www.lfd.uci.edu/~gohlke/pythonlibs/这个网址找到和你的python版本兼容的opencv-python文件,安装即可。

如果在安装上述库的过程中,命令行出现了如下问题:

说明存在其他版本,要先删干净,用下面的代码即可:

pip uninstall 库名

如果觉得相当烦躁,不知道哪里出了问题,可以卸载掉这些再重新安装,代码为:

pip uninstall 库名

不会对你的电脑造成任何危害(笑),既然如此,就开动脑筋操作你的电脑吧。

总结

关键是版本兼容,也许可以给焦头烂额的你一点解决当下问题的灵光?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值