python 机器学习实战:信用卡欺诈异常值检测

2023-05-16

    今晚又实战了一个小案例,把它总结出来:有些人利用信用卡进行诈骗等活动,如何根据用户的行为,来判断该用户的信用卡账单涉嫌欺诈呢?数据集见及链接:  在这个数据集中,由于原始数据有一定的隐私,因此,每一列(即特征)的名称并没有给出。

    一开始,还是导入库:

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

data = pd.read_csv('creditcard.csv')
#data.head(10)
print (data.shape)

我们发现,最后一列"Class"要么是 0 ,要么是 1,而且是 0 的样本很多,1 的样本很少。这也符合正常情况:利用信用卡欺诈的情况毕竟是少数,大多数人都是守法的公民。由于样本太多了,我们不可能去数 0 和 1 的个数到底是多少。因此,需要做一下统计:

count_class = pd.value_counts(data['Class'],sort = True).sort_index()
print (count_class)

输出结果为:

0 284315
1 492
Name: Class, dtype: int64

结果也显示了,0的个数远远多于1的个数。那么,这样就会使正负样本的个数严重失衡。为了解决这个问题,我们需要针对样本不均衡,提出两种解决方案:过采样和下采样。

      在对样本处理之前,我们需要对样本中的数据先进行处理。我们发现,有一列为 Time ,这一列显然与咱们的训练结果没有直接或间接关系,因此需要把这一列去掉。我们还发现,在 v1 ~v28特征中,取值范围大致在 -1 ~ +1 之间,而Amount 这一类数值非常大,如果我们不对这一列进行处理,这一列对结果的影响,可能非常巨大。因此,要对这一列做标准化:使均值为0,方差为1。 此部分代码如下:

from sklearn.preprocessing import StandardScaler    #导入数据预处理模块
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1,1))   # -1表示系统自动计算得到的行,1表示1列
data = data.drop(['Time','Amount'],axis = 1)  # 删除两列,axis =1表示按照列删除,即删除特征。而axis=0是按行删除,是删除样本
#print (data.head(3))
#print (data['normAmount'])

     解决样本不均衡:两种方法可以采用——过采样和下采样。过采样是对少的样本(此例中是类别为 1 的样本)再多生成些,使 类别为 1 的样本和 0 的样本一样多。而下采样是指,随机选取类别为 0 的样本,是类别为 0 的样本和类别为 1 的样本一样少。下采样的代码如下:

X = data.ix[:,data.columns != 'Class'] #ix 是通过行号和行标签进行取值
y = data.ix[:,data.columns == 'Class']    # y 为标签,即类别
number_records_fraud = len(data[data.Class==1])  #统计异常值的个数
#print (number_records_fraud)  # 492 个
#print (data[data.Class == 1].index)
fraud_indices = np.array(data[data.Class == 1].index)   #统计欺诈样本的下标,并变成矩阵的格式
#print (fraud_indices)
normal_indices = data[data.Class == 0].index   # 记录正常值的索引
random_normal_indices =np.random.choice(normal_indices,number_records_fraud,replace = False) # 从正常值的索引中,选择和异常值相等个数的样本
random_normal_indices = np.array(random_normal_indices)
#print (len(random_normal_indices))  #492 个

under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])  # 将正负样本的索引进行组合
#print (under_sample_indices)   # 984个
under_sample_data = data.iloc[under_sample_indices,:]  # 按照索引进行取值
X_undersample = under_sample_data.iloc[:,under_sample_data.columns != 'Class']  #下采样后的训练集
y_undersample = under_sample_data.iloc[:,under_sample_data.columns == 'Class']   #下采样后的标签

print (len(under_sample_data[under_sample_data.Class==1])/len(under_sample_data)) # 正负样本的比例都是 0.5

      下一步:交叉验证。交叉验证可以辅助调参,使模型的评估效果更好。举个例子,对于一个数据集,我们需要拿出一部分作为训练集(比如 80%),计算我们需要的参数。需要拿出剩下的样本,作为测试集,评估我们的模型的好坏。但是,对于训练集,我们也并不是一股脑地拿去训练。比如把训练集又分成三部分:1,2,3.第 1 部分和第 2 部分作为训练集,第 3 部分作为验证集。然后,再把第 2 部分和第 3 部分作为训练集,第 1 部分作为验证集,然后,再把第 1部分和第 3 部分作为训练集,第 2 部分作为验证集。

from sklearn.cross_validation import train_test_split   # 导入交叉验证模块的数据切分
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state = 0) # 返回 4 个值
#print (len(X_train)+len(X_test))
#print (len(X))

X_undersample_train,X_undersample_test,y_undersample_train,y_undersample_train = train_test_split(X_undersample,y_undersample,test_size = 0.3,random_state = 0)
print (len(X_undersample_train)+len(X_undersample_test))
print (len(X_undersample))

      我们需要注意,对数据进行切分,既要对原始数据进行一定比例的切分,测试时能用到;又要对下采样后的样本进行切分,训练的时候用。而且,切分之前,每次都要进行洗牌。

      下一步:模型评估。利用交叉验证,选择较好的参数

#Recall = TP/(TP+FN)
from sklearn.linear_model import LogisticRegression  #
from sklearn.cross_validation import KFold, cross_val_score  #
from sklearn.metrics import confusion_matrix,recall_score,classification_report #

      先说一个召回率 Recall,这个recall 是需要依据问题本身的含义的,比如,本例中让预测异常值,假设有100个样本,95个正常,5个异常。实际中,对于异常值,预测出来4个,所以,精度就是 80%。也就是说,我需要召回 5 个,实际召回 4 个。

      引入四个小定义:TP、TN、FP、FN。

TP,即 True Positive ,判断成了正例,判断正确;把正例判断为正例了

TN,即 True negative, 判断成了负例,判断正确,这叫去伪;把负例判断为负例了

FP,即False Positive ,判断成了正例,但是判断错了,也就是把负例判断为正例了

FN ,即False negative ,判断成了负例,但是判断错了,也就是把正例判断为负例了

      正则化惩罚项:为了提高模型的泛化能力,需要加了诸如 L1 、L2惩罚项一类的东西,对于这一部分内容,请参见我以前的博客。

def printing_Kfold_scores(x_train_data,y_train_data):
    fold = KFold(len(y_train_data),5,shuffle=False)
    c_param_range = [0.01,0.1,1,10,100] # 惩罚力度参数
    results_table = pd.DataFrame(index = range(len(c_param_range),2),columns = ['C_parameter','Mean recall score'])
    results_table['C_parameter'] = c_param_range

    # k折交叉验证有两个;列表: train_indices = indices[0], test_indices = indices[1]
    j = 0
    for c_param in c_param_range:  # 
        print('------------------------------------------')
        print('C parameter:',c_param)
        print('-------------------------------------------')
        print('')
        
        recall_accs = []
        
        for iteration, indices in enumerate(fold,start=1):   #循环进行交叉验证

            # Call the logistic regression model with a certain C parameter
            lr = LogisticRegression(C = c_param, penalty = 'l1')  #实例化逻辑回归模型,L1 正则化

            # Use the training data to fit the model. In this case, we use the portion of the fold to train the model
            # with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1]
            lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())#  套路:使训练模型fit模型

            # Predict values using the test indices in the training data
            y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)# 利用交叉验证进行预测

            # Calculate the recall score and append it to a list for recall scores representing the current c_parameter
            recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample) #评估预测结果
            recall_accs.append(recall_acc)
            print('Iteration ', iteration,': recall score = ', recall_acc)

        # The mean value of those recall scores is the metric we want to save and get hold of.
        results_table.ix[j,'Mean recall score'] = np.mean(recall_accs)
        j += 1
        print('')
        print('Mean recall score ', np.mean(recall_accs))
        print('')

    best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']
    
    # Finally, we can check which C parameter is the best amongst the chosen.
    print('*********************************************************************************')
    print('Best model to choose from cross validation is with C parameter = ', best_c)
    print('*********************************************************************************')
    
    return best_c

运行:

best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)

上面程序中,我们选择进行 5 折的交叉验证,对应地选择了5个惩罚力度参数:0.01,0.1,1,10,100。不同的惩罚力度参数,得到的 Recall 是不一样的。 

C parameter: 0.01
-------------------------------------------

Iteration 1 : recall score = 0.958904109589
Iteration 2 : recall score = 0.917808219178
Iteration 3 : recall score = 1.0
Iteration 4 : recall score = 0.972972972973
Iteration 5 : recall score = 0.954545454545

Mean recall score 0.960846151257

-------------------------------------------
C parameter: 0.1
-------------------------------------------

Iteration 1 : recall score = 0.835616438356
Iteration 2 : recall score = 0.86301369863
Iteration 3 : recall score = 0.915254237288
Iteration 4 : recall score = 0.932432432432
Iteration 5 : recall score = 0.878787878788

Mean recall score 0.885020937099

-------------------------------------------
C parameter: 1
-------------------------------------------

Iteration 1 : recall score = 0.835616438356
Iteration 2 : recall score = 0.86301369863
Iteration 3 : recall score = 0.966101694915
Iteration 4 : recall score = 0.945945945946
Iteration 5 : recall score = 0.893939393939

Mean recall score 0.900923434357

-------------------------------------------
C parameter: 10
-------------------------------------------

Iteration 1 : recall score = 0.849315068493
Iteration 2 : recall score = 0.86301369863
Iteration 3 : recall score = 0.966101694915
Iteration 4 : recall score = 0.959459459459
Iteration 5 : recall score = 0.893939393939

Mean recall score 0.906365863087

-------------------------------------------
C parameter: 100
-------------------------------------------

Iteration 1 : recall score = 0.86301369863
Iteration 2 : recall score = 0.86301369863
Iteration 3 : recall score = 0.966101694915
Iteration 4 : recall score = 0.959459459459
Iteration 5 : recall score = 0.893939393939

Mean recall score 0.909105589115

*********************************************************************************
Best model to choose from cross validation is with C parameter = 0.01
*********************************************************************************

 接下来,介绍混淆矩阵。虽然上面的

def plot_confusion_matrix(cm, classes,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=0)
    plt.yticks(tick_marks, classes)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
混淆矩阵的计算:

import itertools
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample = lr.predict(X_test_undersample.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test_undersample,y_pred_undersample)
np.set_printoptions(precision=2)

print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))

# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
                      , classes=class_names
                      , title='Confusion matrix')
plt.show()

结果如下:

Recall metric in the testing dataset: 0.931972789116


我们发现:

lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred = lr.predict(X_test.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test,y_pred)
np.set_printoptions(precision=2)

print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))

# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
                      , classes=class_names
                      , title='Confusion matrix')
plt.show()
Recall metric in the testing dataset: 0.918367346939

运行:

best_c = printing_Kfold_scores(X_train,y_train)

C parameter: 0.01
-------------------------------------------

Iteration 1 : recall score = 0.492537313433
Iteration 2 : recall score = 0.602739726027
Iteration 3 : recall score = 0.683333333333
Iteration 4 : recall score = 0.569230769231
Iteration 5 : recall score = 0.45

Mean recall score 0.559568228405

-------------------------------------------
C parameter: 0.1
-------------------------------------------

Iteration 1 : recall score = 0.567164179104
Iteration 2 : recall score = 0.616438356164
Iteration 3 : recall score = 0.683333333333
Iteration 4 : recall score = 0.584615384615
Iteration 5 : recall score = 0.525

Mean recall score 0.595310250644

-------------------------------------------
C parameter: 1
-------------------------------------------

Iteration 1 : recall score = 0.55223880597
Iteration 2 : recall score = 0.616438356164
Iteration 3 : recall score = 0.716666666667
Iteration 4 : recall score = 0.615384615385
Iteration 5 : recall score = 0.5625

Mean recall score 0.612645688837

-------------------------------------------
C parameter: 10
-------------------------------------------

Iteration 1 : recall score = 0.55223880597
Iteration 2 : recall score = 0.616438356164
Iteration 3 : recall score = 0.733333333333
Iteration 4 : recall score = 0.615384615385
Iteration 5 : recall score = 0.575

Mean recall score 0.61847902217

-------------------------------------------
C parameter: 100
-------------------------------------------

Iteration 1 : recall score = 0.55223880597
Iteration 2 : recall score = 0.616438356164
Iteration 3 : recall score = 0.733333333333
Iteration 4 : recall score = 0.615384615385
Iteration 5 : recall score = 0.575

Mean recall score 0.61847902217

*********************************************************************************
Best model to choose from cross validation is with C parameter = 10.0
*********************************************************************************

我们发现:

lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train,y_train.values.ravel())
y_pred_undersample = lr.predict(X_test.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test,y_pred_undersample)
np.set_printoptions(precision=2)

print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))

# Plot non-normalized confusion matrix 
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
                      , classes=class_names
                      , title='Confusion matrix')
plt.show()

结果:

Recall metric in the testing dataset: 0.619047619048


我们发现:

    设置阈值。

lr = LogisticRegression(C = 0.01, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)#原来时预测类别值,而此处是预测概率。方便后续比较

thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]

plt.figure(figsize=(10,10))

j = 1
for i in thresholds:
    y_test_predictions_high_recall = y_pred_undersample_proba[:,1] > i
    
    plt.subplot(3,3,j)
    j += 1
    
    # Compute confusion matrix
    cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
    np.set_printoptions(precision=2)

    print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))

    # Plot non-normalized confusion matrix
    class_names = [0,1]
    plot_confusion_matrix(cnf_matrix
                          , classes=class_names
                          , title='Threshold >= %s'%i) 

结果:


      换种思路,采用上采样,进行数据增广。

import pandas as pd
from imblearn.over_sampling import SMOTE #上采样库,导入SMOTE算法
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
credit_cards=pd.read_csv('creditcard.csv')

columns=credit_cards.columns
# The labels are in the last column ('Class'). Simply remove it to obtain features columns
features_columns=columns.delete(len(columns)-1)

features=credit_cards[features_columns]
labels=credit_cards['Class']
features_train, features_test, labels_train, labels_test = train_test_split(features, 
                                                                            labels, 
                                                                            test_size=0.2, 
                                                                            random_state=0)
oversampler=SMOTE(random_state=0)  #实例化参数,只对训练集增广,测试集不动
os_features,os_labels=oversampler.fit_sample(features_train,labels_train)# 使 0 和 1 样本相等
os_features = pd.DataFrame(os_features)
os_labels = pd.DataFrame(os_labels)
best_c = printing_Kfold_scores(os_features,os_labels)

参数选择的结果:

C parameter: 0.01
-------------------------------------------

Iteration 1 : recall score = 0.890322580645
Iteration 2 : recall score = 0.894736842105
Iteration 3 : recall score = 0.968861347792
Iteration 4 : recall score = 0.957595541926
Iteration 5 : recall score = 0.958430881173

Mean recall score 0.933989438728

-------------------------------------------
C parameter: 0.1
-------------------------------------------

Iteration 1 : recall score = 0.890322580645
Iteration 2 : recall score = 0.894736842105
Iteration 3 : recall score = 0.970410534469
Iteration 4 : recall score = 0.959980655302
Iteration 5 : recall score = 0.960178498807

Mean recall score 0.935125822266

-------------------------------------------
C parameter: 1
-------------------------------------------

Iteration 1 : recall score = 0.890322580645
Iteration 2 : recall score = 0.894736842105
Iteration 3 : recall score = 0.970454796946
Iteration 4 : recall score = 0.96014552489
Iteration 5 : recall score = 0.960596168431

Mean recall score 0.935251182603

-------------------------------------------
C parameter: 10
-------------------------------------------

Iteration 1 : recall score = 0.890322580645
Iteration 2 : recall score = 0.894736842105
Iteration 3 : recall score = 0.97065397809
Iteration 4 : recall score = 0.960343368396
Iteration 5 : recall score = 0.960530220596

Mean recall score 0.935317397966

-------------------------------------------
C parameter: 100
-------------------------------------------

Iteration 1 : recall score = 0.890322580645
Iteration 2 : recall score = 0.894736842105
Iteration 3 : recall score = 0.970543321899
Iteration 4 : recall score = 0.960211472725
Iteration 5 : recall score = 0.960903924995

Mean recall score 0.935343628474

*********************************************************************************
Best model to choose from cross validation is with C parameter = 100.0
*********************************************************************************

打印一下混淆矩阵的结果:

lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(os_features,os_labels.values.ravel())
y_pred = lr.predict(features_test.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(labels_test,y_pred)
np.set_printoptions(precision=2)

print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))

# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
                      , classes=class_names
                      , title='Confusion matrix')
plt.show()
Recall metric in the testing dataset: 0.90099009901

总结:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 机器学习实战:信用卡欺诈异常值检测 的相关文章

  • 从 RabbitMQ 迁移到 Amazon SQS [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我们的初创公司目前正在使用RabbitMQ with Python Django 对于消息队列 现在我们计划转移到Amazon SQS其高可用性
  • numba.prange 性能不佳

    我试图整理一个简单的例子来说明使用的好处numba prange对于我自己和一些同事来说 但我无法获得像样的加速 我编写了一个简单的一维扩散求解器 它本质上是在一个长数组上循环 组合元素i 1 i and i 1 并将结果写入element
  • 在自定义 Dask 图中包含关键字参数 (kwargs)

    我正在使用 Dask 为一项操作构建自定义图表 熟悉如何将参数传递给 Dask 图中的函数 并阅读了docs http dask pydata org en latest custom graphs html 然而似乎还是缺少了一些东西 D
  • TypeError:无法在 re.findall() 中的类似字节的对象上使用字符串模式

    我正在尝试学习如何自动从页面获取网址 在下面的代码中 我试图获取网页的标题 import urllib request import re url http www google com regex r pattern re compile
  • PyPDF2 复制后返回空白 PDF

    def EncryptPDFFiles password directory pdfFiles success 0 Get all PDF files from a directory for folderName subFolders f
  • Pandas 将 NULL 读取为 NaN 浮点数而不是 str [重复]

    这个问题在这里已经有答案了 给定文件 cat test csv a b c NULL d e f g h i j k l m n 其中第三列被视为str 当我对列执行字符串函数时 pandas已阅读NULLstr 作为一个NaN float
  • python subprocess proc.stderr.read() 引入额外的行?

    我想运行一些命令并抓取输出到 stderr 的任何内容 我有两个版本的函数可以执行此操作 版本 1 def Getstatusoutput cmd Return status output of executing cmd in a she
  • Python 字典不按顺序排列

    我创建了一个字母表字典 其值从0开始 并根据单词文件增加一定的量 我对最初的字典进行了硬编码 我希望它保持按字母顺序排列 但事实并非如此 我希望它按字母顺序返回字典 基本上与初始字典保持相同 我怎样才能保持秩序 from wordData
  • QFileDialog 作为 TableView 的编辑器:如何获取结果?

    我正在使用一个QFileDialog作为某些专栏的编辑QTableView 这基本上有效 对一些焦点问题取模 请参阅here https stackoverflow com questions 22854242 qfiledialog as
  • Python OO程序结构规划

    我是 OOP 的初学者 我想创建一个包含三个类 A B 和 C 的程序 该类的每个实例都由一组特征 Achar1 Achar2 等定义 该程序应该创建uses由 A 元素 B 元素和 C 元素以及开始日期和结束日期组成 A 和 B 都有子类
  • Django 视图中的原始 SQL 查询

    我将如何使用原始 SQL 执行以下操作views py from app models import Picture def results request all Picture objects all yes Picture objec
  • 如何从 google place api for python 中的地点 id 获取地点详细信息

    我正在使用 Google Places API 和 Python 来构建一个食品集体智能应用程序 例如周围有哪些餐馆 他们的评级如何 营业时间是什么 等等 我正在Python中执行以下操作 from googleplaces import
  • 将误差线添加到 3D 绘图

    我找不到在 matplotlib 的 3D 散点图中绘制误差条的方法 基本上 对于以下代码段 from mpl toolkits mplot3d import axes3d import matplotlib pyplot as plt f
  • 在地图类型中创建 DataFrame 分组列

    My 数据框具有以下结构 df spark createDataFrame B a 10 B b 20 C c 30 Brand Type Amount df show Brand Type Amount B a 10 B b 20 C c
  • 如何在Python中比较枚举?

    从 Python 3 4 开始 Enum类存在 我正在编写一个程序 其中一些常量具有特定的顺序 我想知道哪种方式最适合比较它们 class Information Enum ValueOnly 0 FirstDerivative 1 Sec
  • 树莓派上的 /dev/mem 访问被拒绝

    我正在使用我的 Raspberry Pi 并且正在编写一个 cgi python 脚本 该脚本创建一个网页来控制我的 gpio 输出引脚 当我尝试将 RPi GPIO 作为 GPIO 导入时 我的脚本崩溃了 这是我收到的错误 File co
  • 为什么 `Pool.map()` 多处理中的内存消耗急剧增加?

    我正在对 pandas 数据帧进行多重处理 方法是将其拆分为多个数据帧 这些数据帧存储为列表 并且 使用Pool map 我将数据帧传递给定义的函数 我的输入文件约为 300 mb 因此小数据帧大约为 75 mb 但是 当多处理运行时 内存
  • 在 django 视图中执行阻塞请求

    在我的 django 应用程序的一个视图中 我需要执行相对较长的网络 IO 操作 问题是其他请求必须等待该请求完成 即使它们与该请求无关 我做了一些研究并偶然发现了 Celery 但据我了解 它用于执行独立于请求的后台任务 所以我不能使用任
  • Python 和 Visual Studio Code - 如何在编辑器中运行特定文件?

    我正在使用 Visual Studio Code 和 Python 编写一个小型应用程序 我的应用程序有两个文件 Main py and MyCustomClass py Main py是应用程序的入口点 MyCustomClass py包
  • 通过 subprocess.communicate 在 python 脚本之间传输 pickled 对象输出

    我有两个 python 脚本 object generator py 它会腌制给定的对象并打印它 另一个脚本 object consumer py 通过 subprocess communicate 选择第一个脚本的输出 并尝试使用 pic

随机推荐

  • matlab---s函数讲解之二连杆动力学仿真

    matlab虽然后simulink xff0c 但是再复杂系统的仿真的时候简单的simulink中模块不能满足要求 xff0c 因此需要自己建立s函数 xff0c 作为仿真中的一个模块 在控制系统中分为控制器和被控对象 matlab s函数
  • 全球定位系统的组成

    一 空间部分 1 GPS卫星 Block xff08 试验卫星 xff09 Block xff08 以下均为工作卫星 xff09 14天导航电文 xff0c 实施SA和AS的能力 Block A 180天导航电文 xff0c 卫星互相通信能
  • 前端疑难杂症集锦

    一 webpack打包时Cannot resolve module 39 fs 39 在webpack config js中添加 node fs 34 empty 34 二 typescript找不到fs模块 code npm instal
  • 基于ROS的语音控制机器人(二):上位机的实现

    文章目录 目录 文章目录 前言 一 准备工作 1 python工作环境 2 ros环境 3 QT designer 二 界面程序设计 1 界面设计 2 ui文件转py文件 三 上位机程序编写 1 具体思路 2 具体实现 3 遇到的问题 1
  • "指定的文件格式无法识别或为不支持的二进制"

    次奥 xff0c 你没有正确设置启动项目 转载于 https www cnblogs com tupx p 3701598 html
  • Linux安装MySQL8.0.16

    1 下载安装包 https www mysql com 2 安装MySQL 将下载好的安装包上传到服务器 然后解压 tar xvf mysql 8 0 16 el7 x86 64 tar gz 然后将解压目录重命名为mysql 8 0 16
  • 硬件中断和软件中断的区别

    中断 中断指当出现需要时 xff0c CPU暂时停止当前程序的执行转而执行处理新情况的程序和执行过程 即在程序运行过程中 xff0c 系统出现了一个必须由CPU立即处理的情况 xff0c 此时 xff0c CPU暂时中止程序的执行转而处理这
  • 嵌入式C语言自我修养笔记1-ARM体系结构与编译运行

    目录 ARM 体系结构ARM 体系结构ARM 汇编指令ARM 寻址方式ARM 伪指令C 与汇编混合编程 程序编译链接与安装运行预处理过程编译过程链接过程程序安装apt get链接静态库动态链接共享库插件工作原理Linux 内核模块运行机制L
  • Renode应用:在RISC-V核上运行FreeRTOS

    本篇记录通过Renode在RISC V核上运行FreeRTOS demo的情况 本来不准备写这一篇 xff0c 但是发现近期工作学习密度实在太大 xff0c 上周工作的中间结果这周竟然完全想不起来了 xff0c 不得不又花了一些时间从头摸索
  • VideoStream流媒体(VOD视频点播)系统平台

    软件介绍 xff1a VideoStream是集流媒体视频服务和流媒体应用管理为一体的综合流媒体服务系统 xff0c 本产品通过宽带IP网络为教育系统 各类运营商 政府企业等用户提供音视频服务的应用 系统特点 xff1a 1 采用WEB端口
  • c语言实现模拟FTP服务器项目

    下载源码后 xff0c 直接可以在ubuntu中编译运行 xff1a FTP服务器程序功能 xff1a 客户端 xff1a 1 输入命令 xff1a help 查看FTP服务器所支持的所有命令 2 输入名 xff1a ls 查看服务器上可以
  • 基于ArUco的视觉定位

    参考如下 博客 基于ArUco的视觉定位 1 3 https www freesion com article 4265319144 基于ArUco的视觉定位 4 https www pianshen com article 2491452
  • 伺服电机和步进电机的区别

    硬件型号 xff1a 三菱伺服电机HG KR43J 系统版本 xff1a 电机系统 1 控制的方式不同 步进电机 xff1a 通过控制脉冲的个数控制转动角度的 xff0c 一个脉冲对应一个步距角 伺服电机 xff1a 通过控制脉冲时间的长短
  • ubutnu更换国内源后,更新一直出现404,Not Found的问题

    1 问题 题主系统是ubuntu16 04 64位系统 尝试更换国内各种源 连ubuntu官方源都尝试了 sudo vim etc apt sources list修改为 deb https mirrors tuna tsinghua ed
  • Python+Flask实现股价查询系统。Python绘制股票k线走势

    文章目录 一 实现效果图二 实现思路1 获取数据 2 可视化数据三 源码获取 一 实现效果图 打开默认显示半年线 xff0c 可以通过可视化类型选择可视化k线图 高低点等 xff08 目前只完成了初版 xff0c 当查询的股票数据返回为空时
  • Failed to fetch http://mirrors.tuna.tsinghua.edu.cn/ubuntu/pool/main/g/gcc-5/g++-5_5.4.0-6ubuntu1~16

    今天在ubutun中在安装redis过程中 xff0c 安装gcc时遇到了Failed to fetch http mirrors tuna tsinghua edu cn ubuntu pool main g gcc 5 g 43 43
  • 切换日语输入法找不到MicrosoftIME键盘选项了

    去微软官方下载一个 Microsoft IME office 2010后 xff0c 安装解决 转载于 https www cnblogs com tupx p 3816026 html
  • msgid 属性

    Android源码中的String xml文件 xff0c msgid这个属性是干嘛的 xff1f 全局资源 xff0c 方便引用 比如在布局的text和activity中用到 转载于 https www cnblogs com Ph on
  • 2017年09月23日普级组 数列

    Description 小S今天给你出了一道找规律题 xff0c 题目如下 xff1a 有如下的数列1 xff0c 11 xff0c 21 xff0c 1211 xff0c 111221 xff0c 312211 xff0c 小S问你这个数
  • python 机器学习实战:信用卡欺诈异常值检测

    今晚又实战了一个小案例 xff0c 把它总结出来 xff1a 有些人利用信用卡进行诈骗等活动 xff0c 如何根据用户的行为 xff0c 来判断该用户的信用卡账单涉嫌欺诈呢 xff1f 数据集见及链接 xff1a 在这个数据集中 xff0c