Installation – Python 3.7 with Tensorflow failed. What should I do?

My environment list:

  1. Python 3.7 on Windows 10
  2. pip install tensorflow from Anaconda.
    My Tensorflow version is Tensorflow-1.13.1

  3. I installed Keras and OpenCV Python using the anaconda prompt
    (pip install xxx).

Here is my code:

import os
Import numpy as np
import pandas as pd
Import as sns seaborn
import matplotlib.pyplot as plt
import from PIL image
Import Glob
import cv2
from sklearn.model_selection import train_test_split
from keras.layers import dropout, dense
from keras.models import Sequential, load_model
from keras.layers.normalization Import BatchNormalization
from keras.applications import VGG16
import from sklearn.metrics precision_score, confusion_matrix

human_expression = glob.glob ("E: / expression / sad / *");
print ("Number of images in sad emotion:" + str (len (human_expression)));

When I wrote some Python codes with PyCharm. I can not create the project properly.
The problems are below:

Use TensorFlow backend. Traceback (last call last): file
"D:  Anaconda3  lib  site-packages  tensorflow  python  pywrap_tensorflow.py",
Line 58, in 
    from tensorflow.python.pywrap_tensorflow_internal import * file "D:  Anaconda3  lib  site-packages  tensorflow  python  pywrap_tensorflow_internal.py",
Line 28, in 
    _pywrap_tensorflow_internal = swig_import_helper () file "D:  Anaconda3  lib  site-packages  tensorflow  python  pywrap_tensorflow_internal.py",
Line 24 in swig_import_helper
_mod = imp.load_module ("_pywrap_tensorflow_internal", fp, pathname, description) File "D:  Anaconda3  lib  imp.py", line 242, in
load_module
Return load_dynamic (name, filename, file) D:  Anaconda3  lib  imp.py file, line 342, in load_dynamic
return _load (spec) ImportError: DLL loading failed: 找不到: 的 模块 模块

While handling the exception above, another exception occurred:

Traceback (last call last): file "E: /PythonProject/Test.py",
Line 10, in 
    from keras.layers import dropout, density file "D:  Anaconda3  lib  site-packages  keras  __ init__.py", line 3, in

    from . import utils file "D:  Anaconda3  lib  site-packages  keras  utils  __ init__.py", line 6, in

    from . Import the file conv_utils "D:  Anaconda3  lib  site-packages  keras  utils  conv_utils.py", line 9, into

    from .. import the backend as a K-file "D:  Anaconda3  lib  site-packages  keras  backend  __ init__.py", line 89,
in the 
    import from .tensorflow_backend * file "D:  Anaconda3  lib  site-packages  keras  backend  tensorflow_backend.py",
Line 5, in 
    tensorflow as tf import file "D:  Anaconda3  lib  site-packages  tensorflow  __ init__.py", line 24, in

    from tensorflow.python import pywrap_tensorflow # pylint: disable = unused-import File
"D:  Anaconda3  lib  site-packages  tensorflow  python  __ init__.py", line
49, in 
    from tensorflow.python import pywrap_tensorflow file "D:  Anaconda3  lib  site-packages  tensorflow  python  pywrap_tensorflow.py",
Line 74, in 
    raise ImportError (msg) ImportError: Traceback (last call last): File
"D:  Anaconda3  lib  site-packages  tensorflow  python  pywrap_tensorflow.py",
Line 58, in 
    from tensorflow.python.pywrap_tensorflow_internal import * file "D:  Anaconda3  lib  site-packages  tensorflow  python  pywrap_tensorflow_internal.py",
Line 28, in 
    _pywrap_tensorflow_internal = swig_import_helper () file "D:  Anaconda3  lib  site-packages  tensorflow  python  pywrap_tensorflow_internal.py",
Line 24 in swig_import_helper
_mod = imp.load_module ("_pywrap_tensorflow_internal", fp, pathname, description) File "D:  Anaconda3  lib  imp.py", line 242, in
load_module
Return load_dynamic (name, filename, file) D:  Anaconda3  lib  imp.py file, line 342, in load_dynamic
return _load (spec) ImportError: DLL loading failed: 找不到: 的 模块 模块


Loading the native TensorFlow runtime failed.

See https://www.tensorflow.org/install/errors

for a few common reasons and solutions. Include the entire stack trace
above this error message if you ask for help.

Operation terminated with exit code 1

Python – Executes the next command without waiting for the end of the first

Good evening guys.

I have the following function to create a progress bar:

def progress_bar (p_value, p_max: int):
"" "
: 70 = is the size of the bar
: param p_value: value passed through by a loopback
: param p_max: Specifies the total amount of data that will be iterated
: return:
"" "
Character = int (p_value * 40 / float (p_max))
Percent = int ((p_value / float (p_max)) * 100)
sys.stdout.write ("") + sys.stdout.write ("#" * characters)
sys.stdout.write ("" * (40 characters + 2))
if p_value> = p_max:
sys.stdout.write ("done.  n  n")
otherwise:
sys.stdout.write ("[%3i%%]% Percent)
sys.stdout.flush ()

Now I need to call them in the For loop below so that the bar is within the frame created by the top and bottom pressures.
The top pressure is okay, it produces good results, but the bottom one will not be created until the for loop is finished.

How do I create everything and load the progress bar inside the square?

It is more a question of aesthetics.

print ("╔══════════════════════════════════════════════ ══════════════════════════════╗ ")
for i item in list (p_list):
progress_bar (i + 1, len (p_list))
print ("║" + item.ljust (75) + "║")
print ("╚══════════════════════════════════════════════ ══════════════════════════════╝ ")

Thanks for the support.

python – Population dynamic simulation for the conservation of biological information 2

This question is the follow up to this previous question.

background

With this simulation, I am investigating a system in which enzymes multiply in cells. During the replication of enzymes, parasites can arise by mutation. You can let the system die out. I am interested in where coexistence is possible in parameter space.

I have made the changes recommended by HoboProber. Namely correction of the style and implementation of the model, citing Numpy. Now the system is a two-dimensional array. Cells are the rows of the array. The values ​​of the first column are the number of enzymes and the values ​​of the second column are the number of parasites.

My request

The speed of the new implementation is already much better than the previous one. But I would like to grow there population and gen_max Every little increase in performance counts.
So far I have studied the system with population sizes between 100 and 1000 cells and with a maximum number of generations of 10000. The extent of increase in population size depends on performance. One million cells would be a perfectly reasonable assumption with respect to the modeled system. The maximum number of generations should be 20-30000.

  • Does the code use vectorization and Numpy as effectively as possible in the first place? For example, Where should I pay attention to C-Ordering and F-Ordering, or at all?
  • In that case, could performance benefit from using multithreading / multiprocessing? For example, When the proliferation of molecules takes place, the replication events in different cells are independent of each other. They could possibly happen in parallel.
  • Could performance benefit from using static typing and compilation? For example, with Cython or Numba.

Of course, every advice is greatly appreciated! (For example, when writing data to a file more effectively.)

The code

# - * - Coding: utf-8 - * -
"" "
Collect data on an enzyme-parasite system that explicitly requires subdivision.

features
---------
Simulation()
Simulate the mentioned system.

write_out_file ()
Write data to the CSV output file.
"" "
Import CSV
import time
Import numpy as np


Def simulation (Population_Size, Cell_Size, Replication_Rate_P, Mutation_Rate, Gen_Max):
"" "
Simulate an enzyme-parasite system that explicitly requires compartmentalization.

parameter
----------
population_size: int
The number of cells.

cell_size: int
The maximum number of replicators of cells where cell division occurs.

replication_rate_p: int or float
The fitness (replication rate) of the parasites
relative to the suitability (replication rate) of the enzymes.
example
-------
$ replication_rate_p = 2
This means that the fitness of the parasite is twice as high as that of the enzymes.

mutation_rate: int or float
The probability of a mutation during a replication event.

gen_max: int
The maximum number of generations.
One generation corresponds to an outer cycle.
When the system is extinct, the number of generations does not reach gen_max.

yield
-------
generator object
Contains data about the simulated system.
"" "
Def Fitness (population):
"" "
Calculate the fitness of cells.
Fitness of a cell = number of enzymes / (number of enzymes + number of parasites)

parameter
---------
Population: ndarray
The system itself.

return
------
ndarray
The fitness of every cell of the system.
"" "
Return of the population[:, 0]/population.sum(axis=1)

def population_stats (population):
"" "
Calculate the statistics of the system.

parameter
---------
Population: ndarray
The system itself.

return
-------
tuple
Contains statistics of the simulated system.
"" "
gyak_sums = population.sum (axis = 0)
gyak_means = population.mean (axis = 0)
gyak_variances = population.var (axis = 0)
gyak_percentiles_25 = np.percentile (population, 25, axis = 0)
gyak_medians = np.median (population, axis = 0)
gyak_percentiles_75 = np.percentile (population, 75, axis = 0)
fitness_list = fitness (population)
Return (
gyak_sums[0]gyak_sums[1], (Population[:, 0] > 1) .sum (),
gyak_means[0], gyak_variances[0].
gyak_percentiles_25[0]gyak_medians[0]gyak_percentiles_75[0].
gyak_means[1], gyak_variances[1].
gyak_percentiles_25[1]gyak_medians[1]gyak_percentiles_75[1].
fitness_list.mean (), fitness_list.var (),
np.percentile (fitness_list, 25),
np.median (fitness_list),
np.percentile (fitness_list, 75)
)

# Creating the system with the initial state
# Semicircular cells that contain only enzymes.
population = np.zeros ((population_size, 2), dtype = int)
population[:, 0] = int (cell_size // 2)
gen = 0
Yield (Gen, * Population_Stats (Population), Population_Size,
cell_size, mutation_rate, replication_rate_p, "aft")
print (f "N = {population_size}, rMax = {cell_size},"
f "aP = {replication_rate_p}, U = {mutation_rate}")

while population.size> 0 and gen <gen_max:
gen + = 1

# Replicator proliferation until cell_size in each cell.
while np.any (population.sum (axis = 1) <cell_size):
# Calculate the probability of selecting a parasite for replication.
repl_probs_p = population[population.sum(axis=1) < cell_size].Copy()
repl_probs_p[:, 1] * = replication_rate_p
repl_probs_p = repl_probs_p[:, 1]/repl_probs_p.sum(axis=1)
# Determine if an enzyme or a parasite is replicating
# and when an enzyme replicates, it mutates into a parasite.
# (The result may vary between cells, parasites do not mutate.)
repl_choices = np.random.random_sample (repl_probs_p.shape[0])
mut_choices = np.random.random_sample (repl_probs_p.shape[0])
lucky_replicators = np.zeros (repl_probs_p.shape[0], dtype = int)
lucky_replicators[
                (repl_choices < repl_probs_p) | (mut_choices < mutation_rate)
                ] = 1
population[Populationsum(axis=1)[Populationsum(axis=1)[populationsum(axis=1)[populationsum(axis=1)< cell_size, lucky_replicators] += 1

        if gen % 100 == 0:
            yield (gen, *population_stats(population), population_size,
                   cell_size, mutation_rate, replication_rate_p, "bef")

        # Each cell divides.
        new_population = np.empty_like(population)
        new_population[:, 0] = np.random.binomial(population[:, 0], 0.5)
        new_population[:, 1] = np.random.binomial(population[:, 1], 0.5)
        population -= new_population

        # Discarding dead cells.
        population = np.concatenate([population[population[:, 0] > 1,].
neue_bevölkerung

neue_bevölkerung[new_population[new_population[:, 0] > 1,]])

# Select survival cells according to their fitness
# if there are more viable cells than population_size.
# Therefore, cells with a population_size or less move to the next generation.
if (population.size> 0) & (population.shape[0] > Population):
fitness_list = fitness (population)
fitness_list = fitness_list / fitness_list.sum ()
Population = population[Nprandomchoice(populationshape[Nprandomchoice(populationshape[nprandomchoice(populationshape[nprandomchoice(populationshape[0].
Population,
Replace = wrong,
p = fitness_list) ,:]elif population.size == 0:
for i in range (2):
Yield (gen + i, * (0, 0) * 9, number of inhabitants,
cell_size, mutation_rate, replication_rate_p, "aft")
print (generations) are finished, cells are extinct. ")

if (gen% 100 == 0) & (population.size> 0):
Yield (Gen, * Population_Stats (Population), Population_Size,
cell_size, mutation_rate, replication_rate_p, "aft")

if (gen% 1000 == 0) & (population.size> 0):
print (generations) are done. ")


def write_out_file (result, n_run):
"" "
Write data to the CSV output file.

parameter
----------
Result: generator object or list of generator objects
Contains data about the simulated system.

n_run: int
The number of consecutive runs.
"" "
local_time = time.strftime ("% m_% d_% H_% M_% S_% Y", time.localtime (time.time ())
with open ("output_data_" + local_time + ".csv", "w", newline = "") as out_file:
out_file.write (
"gene;"
"eSzamSum; pSzamSum; alive;"
"eSzamAtl; eSzamVar; eSzamAKv; eSzamMed; eSzamFKv;"
pSzamAtl; pSzamVar; pSzamAKv; pSzamMed; pSzamFKv;
"fitAtl; fitVar; fitAKv; fitMed; fitFKv;"
"N; rMax; U; aP; boaSplit  n"
)
out_file = csv.writer (out_file, delimiter = ";")
Counter = 0
print (counter, "/", n_run)
because I result in:
out_file.writerows (i)
Counter + = 1
print (counter, "/", n_run)


RESULT = [simulation(100, 20, 1, 0, 10000)]
RESULT.append (simulation (100, 20, 1, 1, 10000))
N_RUN = 2
write_out_file (RESULT, N_RUN)
# I usually call the functions from another script,
# These last 4 lines are for example only.
`` `

python – Converts the Connected Cells solution from iterative to DFS

In this LeetCode issue, Longest Palindromic Substring, it is listed under Dynamic Programming for Google Interview Preparation. My understanding of dynamic programming is about "recursion + memoization + guessing". In the Python solution for this answer below, I'm not sure where dynamic programming is, if it exists at all. This is Approach 4 under Solutions (translated from Java to Python). Approach 3 is for dynamic programming, but no solution is given.

Is there a dynamic programming here? Or is this just one solution to solve the problem in O (1) space, where the dynamic programming solution needs O (n ^ 2) space?

Class solution:
def longestPalindrome (self, s):
res = ""
for i in range (len (s)):
# odd case, like "aba"
tmp = self.helper (s, i, i)
if len (tmp)> len (res):
res = tmp
# also with "abba"
tmp = self.helper (s, i, i + 1)
if len (tmp)> len (res):
res = tmp
Return res

# get the longest palindrome, l, r are the middle indices
# from the inside to the outside
def helper (self, s, l, r):
while l> = 0 and r <len (s) and s[l] == s[r]:
L - = 1; r + = 1
returns[l+1:r]

Python – Elevator algorithm with external and internal buttons

I was asked to provide a pseudocode to implement the elevator algorithm

Rules are:

1) Internal key External key calls

2) When I am in the elevator and have pressed the internal button, I have to be served before others.

3) optional – driving people in the elevator "on the way"

I did the following in Python, but I do not think it satisfies





import queue

L = queue.Queue (maxsize = 20)
busy = wrong
current = 0

def outside (bottom):
while (not busy):
L.put (floor)


def internally (floor):
while (not busy):
L.put (floor)
go to (floor);
busy = wrong;


def goto (floor):
Electricity = floor;

def main ():
while (not L.empty ()):
a = L.get ();
busy = true;
go to one);

Main();

Thank you

Loading files jpg into Python

I have to find the entire path of some images .jpg but I can not find them.

look, this is a picture where I have my files .jpg:
Path of the pictures

and I use this code:

session_path = "content / drive / my drive / face"
import os
Import again
from glob import glob
Result = [y for x in os.walk(session_path) for y in glob(os.path.join(x[0], & # 39; * .jpg & # 39;))]Result

but the result is an empty array:

[]

I do not know what to do

Automatically generated type notes in Python with static program analysis

There are some tools, such as MonkeyType and PyAnnotate, that let you create type notes in Python through runtime tracing. Is there a way to do this without actually executing the Python programs, d. H. Static way? I would like to do this on a large scale for many different Python files, and I do not think it is feasible for me to do anything (security and time issues).

Window – Can not access Tensorboard, Python

I can not access Tensorboard (http: // DESKTOP-BRLVGMD: 6006). My question is very similar to this one, which unfortunately has no answer.

  • More details to my problem:
    • Name of the folder in the logs: Cats-vs-dogs-CNN
    • File log name: events.out.tfevents.1558182697.DESKTOP-BRLVGMD
    • Operating system: Windows 10 64 bit
    • Python version: 3.7.0
    • Tensorflow Version: 1.13.1 (CPU only)

I'm trying to use Python version: 3.6.2 instead, but no results.

C:  Users  frner  Desktop  TensorFlow  logs> tensorboard --logdir = logs 
TensorBoard 1.13.1 at http: // DESKTOP-BRLVGMD: 6006 (Press CTRL + C to quit the program.)
Tracing (last call last):
File "c:  python3.7  lib  runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:  python3.7  lib  runpy.py", line 85, in _run_code
exec (code, run_globals)
File "C:  Users  frner  AppData  Roaming  Python  Python37  Scripts  tensorboard.exe  __ main__.py", line 9, in 
  File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  tensorboard  main.py", line 57, in run_main
app.run (tensorboard.main, flags_parser = tensorboard.configure)
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  absl  app.py", line 300, is executed
_run_main (main, args)
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  absl  app.py", line 251, in _run_main
sys.exit (main (argv))
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  tensorboard  program.py", line 228, in main
self._register_info (server)
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  tensorboard  program.py", line 274, in _register_info
manager.write_info_file (info)
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  tensorboard  manager.py", line 269, in write_info_file
Payload = "% s  n"% _info_to_string (tensorboard_info)
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  tensorboard  manager.py", line 129, in _info_to_string
for k in _TENSORBOARD_INFO_FIELDS
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  tensorboard  manager.py", line 129, in 
    for k in _TENSORBOARD_INFO_FIELDS
File "C:  Users  frner  AppData  Roaming  Python  Python37  site-packages  tensorboard  manager.py", line 51, in 
    (dt - datetime.datetime.fromtimestamp (0)). total_seconds ()),
OSError: [Errno 22] invalid argument

Python – Calculate the day of the week with the doomsday algorithm

Was too bored during the holidays … here is a code that finds the day of the week using the algorithm in this video. Please provide a logical date in the correct format, as I did not consider incorrect entries because I am too lazy. My code is short and sweet.

Day =["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]    #Some database numbers and strings
mdoom =[3,28,14,4,9,6,11,8,5,10,7,12]
while true:
enter = input (& nbsp;;  nEnter a date in the format dd / mm / yyyy: & # 39;) # input date in a specific format
Date, Month, Year = Map (int, entry.split (& # 39; / & # 39;)) #Read date, month and year
centdoom =[3,2,0,5]
    a = centdoom[((year//100)%4)-3]
    b = (year% 100) // 12
c = (year% 100)% 12
d = c // 4 # Random calculations for the end of the world :)
e = a + b + c + d

if year% 4 == 0: # Check the leap year
mdoom[0]mdoom[1]= 4.29

ddoom = e% 7 # finds a date in the first week that has the same day as the end of the world
r = mdoom[month-1]                                            #Shows the date of the Last Judgment in the month entered
r = r% 7
r = ddoom-r
date = date% 7 # finds a date in the first week that has the same day as the date of the entry
print (& # 39 ;, day[(r+date)%7]# prints the output
k = input (& # 39;  nrepare? (j / n) & # 39;)
if k == & # 39; y & # 39 ;:
continue
otherwise:
break

And suggestions or improvements are welcome.

performance – Python program for "0-1 backpack problem"

With reference to – https://en.wikipedia.org/wiki/Knapsack_problem – this is the definition of a backpack or backpack problem:

knapsack problem

Here is my version of the backpack problem in Python:

def solve_naive (capacity, articles, weights, values):

grid = [[0] * (Capacity + 1)]for articles in assortment (article):
grid.append (grid[item].Copy())
for k in the range (weights[item]Capacity + 1):
grid[item + 1][k]    = max (grid[item][k], Grid[item][K-weights[K-weights[k-Gewichte[k-weights[item]]+ Values[item])

Solution value = grid[items][capacity]
    
    
    
    solution_weight = 0
forgive = []
    k = capacity
for articles in the range (Article, 0, -1):
if grid[item][k]    ! = Grid[item - 1][k]:
taken.append (item - 1)
k - = weights[item - 1]
            solution_weight + = weights[item - 1]

    return solution_value, solution_weight, taken

I would like to know if I could make this code shorter and more efficient.

NOTE 1 – The data is the Nasdaq 100 list of current prices and price estimates for one hundred shares (from one day in 2019). My investment budget is $ 10,000.

NOTE 2 – For your information, the investment (the weight solution) is 999930 cents (9999.30 USD) and the expected return ( solution value) is 1219475 cents (12,194.75 USD).

NOTE 3 – It will take some time for the Nasdaq 100 backpack to run on my computer.

Any help would be appreciated.