0

私のアルゴリズムは数時間実行され、完了したら変数をファイルに保存する必要がありました。ファイルに書き込むときにメモリ例外が原因でクラッシュしましたが...アルゴリズムは機能し、変数には必要な値がありました。この時点でその変数を取得する方法はありますか? ところで、私はPythonを初めて使用します。私が求めていることは少し奇妙であることを完全に認識しています。

# -*- coding: utf-8 -*-
from scipy import *
feature_filename = '4087_features.pkl'
name = 'training'
minimum_features = 3
feature_output = '4087_features_min' + str(minimum_features) + '_' + name + '.txt'

print feature_output

# load necessary files for this step

print 'loading features'
import pickle
features = pickle.load(open(feature_filename, 'rb'))
features_new = {}
t = 0
from scipy.sparse import *
for k in features:
    features_new[k] = t
    t += 1
features = features_new
print feature_filename + ' loaded'

filename_in = '../../../Dropbox/Machinaal_leren/project/project/Emotion_Data_twitter/tweets_' + name + '.mat'
print 'loading ' + filename_in + '...'

import scipy.io
from numpy  import *
try:
    data
    tweets
except NameError:
    data = scipy.io.loadmat(filename_in)
    tweets = data['tweets_' + name].squeeze()
print 'tweets_' + name + 'loaded'

execfile('functions.py')

import numpy as np
from multiprocessing import Pool


t = 0


def create_feature_vector(tweet, ground_truth):
    feature_row = np.array([0] * len(features))
    tweet = clean_tweet(tweet)
    # N-grams
    for N in range(3):
        for j in range(0, len(tweet) - (N - 1)):
            try:
                key = ''
                for m in range(N):
                    key += tweet[j + m] + ' '
                index = features[key]
                feature_row[index] += 1
            except ValueError:
                pass
            except IndexError:
                pass
            except KeyError:
                pass
    count_features = (feature_row != 0).sum(0)
    if(count_features >= minimum_features):
        feature_row = [x / (1.*sum(feature_row)) for x in feature_row]
        return(feature_row, ground_truth)
    else:
        return (9, 9)

emotions = ['emo_joy', 'emo_fear', 'emo_sadness', 'emo_thankfulness', 'emo_anger', 'emo_surprise', 'emo_love']
N_emo = len(emotions)
ground_truth_list = []

for i in range(len(tweets)):
    feature_vector, ground_truth = create_feature_vector(tweets[i][0], emotions.index(tweets[i][1]) + 1)
    print i
    if(i==0):
        feature_vector_matrix =coo_matrix(ground_truth)

    else:
        if((feature_vector != 9) and (ground_truth != 9)):
            ground_truth_list.append(ground_truth)
            feature_vector_matrix = vstack([feature_vector_matrix,coo_matrix(feature_vector)])




print 'Calculated the matrix, ground truth and saving files'


ground_truth_array = np.array(ground_truth_list)

output = open('ground_truth.pkl', 'wb')
pickle.dump(ground_truth_array, output)
output.close()

output2 = open('feature_matrix.pkl', 'wb')
pickle.dump(feature_vector_matrix, output2)
output2.close()

この行の後にクラッシュしました

print '行列の計算、グラウンド トゥルース、ファイルの保存'

出力

Calculated the matrix, ground truth and saving files
Traceback (most recent call last):
  File "C:\Users\Olivier.Janssens\Documents\Aptana Studio 3 Workspace\MachineLearningBNB\generate_feature_vectors.py", line 99, in <module>
    pickle.dump(feature_vector_matrix, output2)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 1370, in dump
    Pickler(file, protocol).dump(obj)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 224, in dump
    self.save(obj)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 419, in save_reduce
    save(state)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 562, in save_tuple
    save(element)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 600, in save_list
    self._batch_appends(iter(obj))
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 615, in _batch_appends
    save(x)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 419, in save_reduce
    save(state)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 663, in _batch_setitems
    save(v)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 419, in save_reduce
    save(state)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 562, in save_tuple
    save(element)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 581, in save_tuple
    self.memoize(obj)
  File "C:\Program Files (x86)\python2.7\lib\pickle.py", line 247, in memoize
    self.memo[id(obj)] = memo_len, obj
MemoryError

99行目は:

pickle.dump(feature_vector_matrix, output2)

私はground_truth.pklを持っていますが、完全に見えます

4

3 に答える 3

0

コードが (非常に大きいと思われる)numpyから配列を作成しようとすると、クラッシュが発生します。ground_truth_list私の提案は、アレイを作成する前にリストをディスクに保存することです。このようにして、常にリストの値を読み取ることができます (Python プロンプトがあるかどうかは関係ありません)。

アップデート

pickle 化できないオブジェクトが (その名前が示すように) マトリックスである場合、考えられる解決策は、それをいくつかのスライスに分割し (または、マトリックス全体ではなくスライスを作成するだけ)、すべてのスライスをディスクに pickle することです。後でそのマトリックスを使用する必要がある場合は、元のマトリックスを復元するために、個々のスライスをロードして再度結合する必要があります。おそらく最も効率的な解決策ではないかもしれませんが、うまくいくはずです。

于 2012-12-07T13:03:04.803 に答える
0

使用するexcept MemoryError

このようにして、メモリ例外が発生した場合に値を受け取ることができます。

次のように使用する必要があります。

try:
   // Your code where you get the error
except MemoryError:
   //save or print your values here

しかし、このクラッシュが頻繁に発生する場合は、コードを最適化する必要があります。非常に大きな処理ステップを探します。プロセスを小さなステップに分割したり、最初に情報を保存したりすると役立つ場合があります。

于 2012-12-07T12:51:55.333 に答える
0

コードに基づくと、ネストされた関数などには含まれていません。Python ウィンドウを開いたままにしておく限り、コードの場合と同様に、変数を取得できるはずです。つまり、Python プロンプトでこのコードを実行するだけです。

ground_truth_array = np.array(ground_truth_list)

output = open('ground_truth.pkl', 'wb')
pickle.dump(ground_truth_array, output)
output.close()

output2 = open('feature_matrix.pkl', 'wb')
pickle.dump(feature_vector_matrix, output2)
output2.close()

まだ Python プロンプトが表示されない場合は、基本的に運が悪く、データを再実行する必要があります。将来、変数を節約したり、より小さなサブセットで機能をテストしたりして、クラッシュによって死亡しないことを確認するために、このことを覚えておいてください。

于 2012-12-07T12:56:49.810 に答える