FileNotFoundError: No such file: 'someones_epi.nii.gzip' - image

I am trying to load an MRI, I keep getting the following error:
Traceback (most recent call last):
File "F:/Study/Projects/BTSaG/Programs/t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 38, in load raise FileNotFoundError("No such file: '%s'" % filename)
FileNotFoundError: No such file: 'someones_epi.nii.gzip'
The code is used is as follows:
import nibabel as nib
epi_img = nib.load('someones_epi.nii.gzip')
epi_img_data = epi_img.get_data()
epi_img_data.shape(53, 61, 33)
import matplotlib.pyplot as plt
def show_slices(slices):
""" Function to display row of image slices """
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower")
slice_0 = epi_img_data[26, :, :]
slice_1 = epi_img_data[:, 30, :]
slice_2 = epi_img_data[:, :, 16]
show_slices([slice_0, slice_1, slice_2])
plt.suptitle("Center slices for EPI image")
I have also updated the loadsave.py file in nibabel but it didn't work. Please help.
Edit:
The earlier error was resolved. Now another error has been encountered.
Traceback (most recent call last):File "F:\Study\Projects\BTSaG\Programs\t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 47, in load filename)
nibabel.filebasedimages.ImageFileError: Cannot work out file type of "someones_epi.nii.gzip"

This is an old question, however I may have the solution for it.
I just figured out that nibabel.save() does not allow me to have dot . or dash - in the folder names. These can exist in filenames however. In your case, the current path is:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\nibabel\someones_epi.nii.gzip
I would change it to:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35_32\Lib\site_packages\nibabel\someones_epi.nii.gzip
This is just to give an example. Of course, I don't mean that you actually change the names of these package folders as it might cause other errors.
The actual solution would be to move the file someones_epi.nii.gzip to the user structure, something like:
C:\Users\AnkitaShinde\Desktop\nibabel\someones_epi.nii.gzip

Related

Sentiment anaysis using Harvard IV-4 dictionary

I was trying to compute the sentiment using Harvard IV-4dictionary.
I installed the "pysentiment" successfully.
I run the following:
import pysentiment as ps
hiv4 = ps.HIV4()
tokens = hiv4.tokenize(text)
score = hiv4.get_score(tokens)
and I got the following error:
Traceback (most recent call last):
File "C:/Users/df/Desk Top/Finalazed/punctuation.py", line 274, in <module>
hiv4 = ps.HIV4()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\base.py", line 55, in __init__
self._tokenizer = Tokenizer()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\utils.py", line 36, in __init__
self._stopset = self.get_stopset()
File "C:\Users\df\AppData\Local\Programs\Python\Python37\lib\site-packages\pysentiment\utils.py", line 52, in get_stopset
fin = open('%s/%s'%(STATIC_PATH, f), 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\df\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\pysentiment\\static/Currencies.txt'
Could any body tell why I am getting this? Thanks.
Do copy pysentiment folder in the given path. Actually pysentiment folder doesnt contain static sub folder. You can check it by diplaying hidden folder "local".

'DataFrame' object has no attribute 'split_frame'

Unable to Split frame using split_frame(). The dataframe is able to show() but I cannot split it. Please help.
Below is a sample of the code I have used.
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator
from __future__ import print_function
temp = spark.read.option("header","true").option("inferSchema","true").csv("hdfs://bda-ns/user/august_week2.csv")
train,test,valid = temp.split_frame(ratios=[.75, .15])
Expected: no error. Data split into test and train data frame.
Actual:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/cloudera/parcels/SPARK2-2.3.0.cloudera2-1.cdh5.13.3.p0.316101/lib/spark2/python/pyspark/sql/dataframe.py", line 1182, in __getattr__
"'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
AttributeError: 'DataFrame' object has no attribute 'split_frame'
>>> train,test,valid = temp.split_frame(ratios=[.75, .15])
Traceback (most recent call last):
File "/opt/cloudera/parcels/SPARK2-2.3.0.cloudera2-1.cdh5.13.3.p0.316101/lib/spark2/python/pyspark/context.py", line 234, in signal_handler
You could use randomsplit on your spark dataframe.
If you want to use the H2O-3 split_frame method, you would first have to convert your spark frame to an h2o frame. In which case you could use hc.as_h2o_frame(spark_df) where hc is your h2o_context (note: you would also need to create the h2o_context for this to work).

how do I set a turtle to an image

I am trying to set my image to a file, but when i run it i get
Exception in Tkinter callback Traceback (most recent call last):
File
"C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
line 1699, in call
return self.func(*args) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 686, in eventfun
fun() File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\RPG.py",
line 20, in up
combat() File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\RPG.py",
line 57, in combat
enemy.shape(image) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 2777, in shape
self.turtle._setshape(name) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 2506, in _setshape
self._item = screen._createimage(screen._shapes["blank"]._data) File
"C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\turtle.py",
line 723, in _createimage
return self.cv.create_image(0, 0, image=image) File "", line 1, in create_image File
"C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
line 2483, in create_image
return self._create('image', args, kw) File "C:\Users\Travi\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
line 2474, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage1" doesn't exist
when I have the file name clearly stated exactly where it is on my pc.
the code
import os
from turtle import Turtle,Screen
print(os.getcwd())
os.chdir('C:\\Users\\Travi\\Downloads')
screen.register_shape("Crawfish_attack.gif")
turtle = Turtle()
turtle.setimage("Crawfish_attack.gif")
thanks in advance
BTW the link is here
and the rest of the code all works and is not needed to be shown
Remove "\\Crawfish_attack" from the os.chdir() arguments. You need to path to the folder it is in, not the file. That is what the register_shape function will do is pull the exact file in that folder.
You were getting the error because you were trying to path to something (it was looking for a folder) that does not exist.
import os
from turtle import Turtle,Screen
print(os.getcwd())
os.chdir('C:\\Users\\Travi\\Downloads')
screen.register_shape("Crawfish_attack.gif")

BrokenPipeError: [WinError 109] The pipe has been ended during data extraction

I am new to multiprocessing in python.I am extracting some features from a list of 70,000 URLs. I have them from 2 different files. After the feature extraction process I pass the result to a list and then to a CSV file.
The code runs but then stops with the error.I tried to catch the error but it produced another one.
Python version = 3.5
from feature_extractor import Feature_extraction
import pandas as pd
from pandas.core.frame import DataFrame
import sys
from multiprocessing.dummy import Pool as ThreadPool
import threading as thread
from multiprocessing import Process,Manager,Array
import time
class main():
lst = None
def __init__(self):
manager = Manager()
self.lst = manager.list()
self.dostuff()
self.read_lst()
def feature_extraction(self,url):
if self.lst is None:
self.lst = []
features = Feature_extraction(url)
self.lst.append(features.get_features())
print(len(self.lst))
def Pool(self,url):
pool = ThreadPool(8)
results = pool.map(self.feature_extraction, url)
def dostuff(self):
df = pd.read_csv('verified_online.csv',encoding='latin-1')
df['label'] = df['phish_id'] * 0
mal_urls = df['url']
df2 = pd.read_csv('new.csv')
df2['label'] = df['phish_id']/df['phish_id']
ben_urls = df2['urls']
t = Process(target=self.Pool,args=(mal_urls,))
t2 = Process(target=self.Pool,args=(ben_urls,))
t.start()
t2.start()
t.join()
t2.join
def read_lst(self):
nw_df = DataFrame(list(self.lst))
nw_df.columns = ['Redirect count','ssl_classification','url_length','hostname_length','subdomain_count','at_sign_in_url','exe_extension_in_request_url','exe_extension_in_landing_url',
'ip_as_domain_name','no_of_slashes_in requst_url','no_of_slashes_in_landing_url','no_of_dots_in_request_url','no_of_dots_in_landing_url','tld_value','age_of_domain',
'age_of_last_modified','content_length','same_landing_and_request_ip','same_landing_and_request_url']
frames = [df['label'],df2['label']]
new_df = pd.concat(frames)
new_df = new_df.reset_index()
nw_df['label'] = new_df['label']
nw_df.to_csv('dataset.csv', sep=',', encoding='latin-1')
if __name__ == '__main__':
start_time = time.clock()
try:
main()
except BrokenPipeError:
print("broken pipe....")
pass
print (time.clock() - start_time, "seconds")
Error Traceback
Process Process-3:
Traceback (most recent call last):
File "F:\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 312, in _recv_bytes
nread, err = ov.GetOverlappedResult(True)
BrokenPipeError: [WinError 109] The pipe has been ended
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
self.run()
File "F:\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "H:\Projects\newoproject\src\main.py", line 33, in Pool
results = pool.map(self.feature_extraction, url)
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 260, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 608, in get
raise self._value
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "F:\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
return list(map(*args))
File "H:\Projects\newoproject\src\main.py", line 26, in feature_extraction
self.lst.append(features.get_features())
File "<string>", line 2, in append
File "F:\Continuum\Anaconda3\lib\multiprocessing\managers.py", line 717, in _callmethod
kind, result = conn.recv()
File "F:\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 250, in recv
buf = self._recv_bytes()
File "F:\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 321, in _recv_bytes
raise EOFError
EOFError
My response is late and does not address the posted problem directly; but hopefully will provide a clue to others who encounter similar errors.
Errors that I encountered:
BrokenPipeError
WinError 109 The pipe has been ended &
WinError 232 The pipe is being closed
Observed with Python 36 on Windows 7, when:
(1) the same async function was submitted multiple times, each time with a different instance of a multiprocessing data store, a Queue in my case (multiprocessing.Manager().Queue())
AND
(2) the references to the Queues were saved in short-life local variables in the enveloping function.
The errors were occurring despite the fact that the Queues, shared with the successfully spawned and executing async-functions, had items and would still be in active use (put() & get()) at the time of exception.
The error consistently occurred when the same async_func was called the 2nd time with a 2nd instance of the Queue. Immediately after apply_async() of the function, the connection to the 1st Queue supplied to the async_func the 1st time, would get broken.
The issue got resolved when the references to the Queues were saved in non-overlapping (like a Queue-list) & longer-life variables (like variables returned to functions higher in the call-stack) in the enveloping function.

TypeError: hasattr(): attribute name must be string in pymc

I have looked at the following links but none of them provide the solution I am looking for
https://github.com/pymc-devs/pymc/issues/125
PyMC error : hasattr(): attribute name must be string
I have to write a function which given the priors (and other stuff like data etc) returns a pymc model.
eg
m = pym.Model([fittable_params.values(), rv])
return m
and the in the calling function, when I do mcmc = pymc.MCMC(model)
It gives a long error
Traceback (most recent call last):
File "model_constructor.py", line 81, in <module>
mcmc = pm.MCMC(model)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/MCMC.py", line 81, in __init__
**kwds)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Model.py", line 195, in __init__
Model.__init__(self, input, name, verbose)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Model.py", line 98, in __init__
ObjectContainer.__init__(self, input)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Container.py", line 605, in __init__
conservative_update(self, input_to_file)
File "/usr/local/lib/python2.7/dist-packages/pymc-2.3.2-py2.7-linux-i686.egg/pymc/Container.py", line 548, in conservative_update
if not hasattr(obj, k):
TypeError: hasattr(): attribute name must be string
On the other hand , if in the function (which returns a model), if I do
m = pm.MCMC([fittable_params.values(), rv])
it is running fine, but the function should return a model so that the user can do whatever he wants with the model in other parts of code.
If the linked solutions don't work for you then as a last resort you can just delete the non-string attributes from the model, since they don't seem to be used anyway.
for key in m.__dict__.keys():
if not isinstance(key, basestring):
del m.__dict__[key]

Resources