Day6--Logistic Regression代码

数据集 | 社交网络

该数据集包含了社交网络中用户的信息。这些信息涉及用户ID,性别,年龄以及预估薪资。一家汽车公司刚刚推出了他们新型的豪华SUV,我们尝试预测哪些用户会购买这种全新SUV。并且在最后一列用来表示用户是否购买。我们将建立一种模型来预测用户是否购买这种SUV,该模型基于两个变量,分别是年龄和预计薪资。因此我们的特征矩阵将是这两列。我们尝试寻找用户年龄与预估薪资之间的某种相关性,以及他是否购买SUV的决定

步骤1 | 数据预处理

导入库

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

导入数据集

这里获取数据集

dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
Y = dataset.iloc[:,4].values

解析:dataset.iloc[:, [2, 3]].values选取的是数据集的年龄和预计薪资这两列,Y为是否购买

将数据集分成训练集和测试集

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)

特征缩放

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

步骤2 | 逻辑回归模型

该项工作的库将会是一个线性模型库,之所以被称为线性是因为逻辑回归是一个线性分类器,这意味着我们在二维空间中,我们两类用户(购买和不购买)将被一条直线分割。然后导入逻辑回归类。下一步我们将创建该类的对象,它将作为我们训练集的分类器。

将逻辑回归应用于训练集

from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(X_train, y_train)

步骤3 | 预测

预测测试集结果

y_pred = classifier.predict(X_test)

步骤4 | 评估预测

我们预测了测试集。 现在我们将评估逻辑回归模型是否正确的学习和理解。因此这个混淆矩阵将包含我们模型的正确和错误的预测。

生成混淆矩阵

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

可视化

from matplotlib.colors import ListedColormap
X_set,y_set=X_train,y_train
X1,X2=np. meshgrid(np. arange(start=X_set[:,0].min()-1, stop=X_set[:, 0].max()+1, step=0.01),
                   np. arange(start=X_set[:,1].min()-1, stop=X_set[:,1].max()+1, step=0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(),X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(),X1.max())
plt.ylim(X2.min(),X2.max())
for i,j in enumerate(np. unique(y_set)):
    plt.scatter(X_set[y_set==j,0],X_set[y_set==j,1],
                c = ListedColormap(('red', 'green'))(i), label=j)

plt. title(' LOGISTIC(Training set)')
plt. xlabel(' Age')
plt. ylabel(' Estimated Salary')
plt. legend()
plt. show()

X_set,y_set=X_test,y_test
X1,X2=np. meshgrid(np. arange(start=X_set[:,0].min()-1, stop=X_set[:, 0].max()+1, step=0.01),
                   np. arange(start=X_set[:,1].min()-1, stop=X_set[:,1].max()+1, step=0.01))

plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(),X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(),X1.max())
plt.ylim(X2.min(),X2.max())
for i,j in enumerate(np. unique(y_set)):
    plt.scatter(X_set[y_set==j,0],X_set[y_set==j,1],
                c = ListedColormap(('red', 'green'))(i), label=j)

plt. title(' LOGISTIC(Test set)')
plt. xlabel(' Age')
plt. ylabel(' Estimated Salary')
plt. legend()
plt. show()

数学建模是一种将实际问题转化为数学语言的过程,通过解决这些问题来得出量化解决方案。以下是四个经典数学建模案例以及简化的示例代码: 1. **人口增长模型** - 梯度增长模型(如 logistic growth model) ```python import numpy as np def population_growth(initial_population, growth_rate, carrying_capacity): time = np.linspace(0, 50, 100) # 时间范围 population = initial_population * (carrying_capacity / (1 + growth_rate * np.exp(-time))) return population # 示例用法 initial_pop = 1000 growth_rate = 0.05 cap_carrying = 10000 population_series = population_growth(initial_pop, growth_rate, cap_carrying) ``` 2. **经济预测模型** - 线性回归模型(如股票价格预测) ```python from sklearn.linear_model import LinearRegression # 假设我们有历史股票数据 data = {'days': [1, 2, 3, ..., 100], 'prices': [10, 11, 12, ..., 20]} model = LinearRegression() model.fit(data['days'].reshape(-1, 1), data['prices']) # 预测未来一的价格 future_day = 101 predicted_price = model.predict([[future_day]]) ``` 3. **物流路线优化** - 贪心算法或遗传算法(如旅行商问题) ```python def tsp(city_list): n = len(city_list) best_path = [city_list[0]] current_city = city_list[0] total_distance = 0 for _ in range(n - 1): min_distance = float('inf') next_city = None for i in range(1, n): if i != current_city and distance_matrix[current_city][i] < min_distance: min_distance = distance_matrix[current_city][i] next_city = i best_path.append(next_city) total_distance += min_distance current_city = next_city best_path.append(best_path[0]) # 关回起点 total_distance += distance_matrix[current_city][0] return best_path, total_distance # 使用示例,假设distance_matrix是一个二维数组存储城市之间的距离 best_route, shortest_distance = tsp(city_list) ``` 4. **电力需求预测** - 时间序列分析(如 ARIMA 或 LSTM) ```python from statsmodels.tsa.arima_model import ARIMA import pandas as pd # 假设有电力消耗时间序列数据 data = pd.read_csv("electricity_consumption.csv") model = ARIMA(data['consumption'], order=(1, 1, 1)) results = model.fit() forecast = results.forecast(steps=10)[0] print("未来10预测电力需求:", forecast) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值