Problem 105. Warning (from warnings module):
File \\
plt.figure(figsize=(12, 8))
UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
Answer: The warning is alerting to a potential issue with Matplotlib's handling of its graphical user interface (GUI) elements when they're not operated within the main thread of a Python application. This is a common concern when working with Matplotlib in environments that aren't straightforward Python scripts, such as web applications, GUI applications, or a script that may be running in a separate thread or an asynchronous context. Here are a few approaches to address or circumvent this warning:
a) Ensure Matplotlib Uses a Non-Interactive Backend: Sometimes, explicitly setting Matplotlib to use a non-interactive backend can prevent it from attempting to use GUI features that are not compatible with non-main threads. We can set this at the beginning of your script with:
import matplotlib
matplotlib.use('Agg') # Use the Anti-Grain Geometry non-interactive backend suited for scripts generating images/files.
b) Ensuring that figures are properly closed after saving can help:
plt.close(fig) # Explicitly close the figure.
Problem 104. "ValueError: Unknown format code 'd' for object of type 'float'" suggests that the format code 'd' used for annotations in the heatmap cannot be applied to floating-point numbers. This is because 'd' is intended for decimal integers, and after replacing 0 with np.nan, pandas automatically converts the integer types to float because np.nan is a floating-point value.
Problem 103. FileNotFoundError: [Errno 2] No such file or directory:
Add r in front of the file or folder directory
Explanation and solution: Such errors appears appears on IDLE shell when the file name or directory is defined by myCSVfile = "C:\GlobalSino20230219\ICs\images3\NaiveBayesClassifier.csv" (with our "r" in front); however, such errors on appears on Cmd/Command Prompt with myCSVfile = r"C:\GlobalSino20230219\ICs\images3\NaiveBayesClassifier.csv". Namely, the error messages appears differently in different code editors.
Problem 102: On "SlideTitleA = extract_substring(ColumnsNames_for_SlideTitle[3]).split("::")[-1]", it says "IndexError: index 3 is out of bounds for axis 0 with size 3"
Solution:
if len(ColumnsNames_for_SlideTitle) >= 4:
SlideTitleA = extract_substring(ColumnsNames_for_SlideTitle[3]).split("::")[-1] print("I have run commons already:", SlideTitleA)
if len(ColumnsNames_for_SlideTitle) == 3:
SlideTitleA = extract_substring(ColumnsNames_for_SlideTitle[2]).split("::")[-1] print("I have run commons already:", SlideTitleA)
else:
print("ColumnsNames_for_SlideTitle does not have enough elements.")
Problem 101: ValueError: attempt to get argmax of an empty sequence
Problem source:
most_popular = Value_counts.idxmax()
Solution:
if not Value_counts.empty:
most_popular = Value_counts.idxmax()
else:
most_popular = None
Problem 100. AttributeError: "int" object has no attribute "to_csv".
Solution: Modify the code of "xyz_csv.to_csv("xyz_csv.csv",index=False)" to "xyz_csv.to_csv("xyz_csv.csv",index=False, encoding='utf-8-sig')" by adding "encoding='utf-8-sig'".
Problem 99. It is not working correctly with .locateOnScreen().
Solution: "thePostion = pg.locateOnScreen(r'C:\GlobalSino\ICs\images\4732g.PNG', confidence =0.8)" needs to be right above pg.moveTo(), pg.click(), and/or thePostion[0]/thePostion[1]; otherwise, the .locateOnScreen() function does not work if it is too far above the pg.moveTo(), pg.click(), and/or thePostion[0]/thePostion[1].
Problem 98. Principle and troubleshooting: Automation of Mouse Movements and Clicks (comparison among pyautogui, pygetwindow, pydirectinput, autoit, Quartz, platform, ctypes, uiautomation and Sikuli). Link
Problem 97. IndexError: .iloc requires numeric indexers, got ['Marks' 'Teacher']
Solution: Use ".loc" instead of ".iloc".
Problem 96. y axis values are not ordered. Code:
![Upload Files to Webpages](images3/2289b.png)
Output:
![Upload Files to Webpages](images3/2289a.png)
Solution: convert y values to float:
![Upload Files to Webpages](images3/2289e.png)
Output:
![Upload Files to Webpages](images3/2289d.png)
Problem 95. CSV problems:
csv_input = csv.reader(f_input)
pandas.errors.ParserError: Error tokenizing data. C error: Expected 4 fields in line x, saw y
Solution: Open it first and then read:
with open(inFile) as f_input:
csv_input = csv.reader(f_input)
for row in csv_input:
print(len(row))
Problem 94. csvwriter.writerows(rows)
io.UnsupportedOperation: not writable
Solution: https://www.globalsino.com/ICs/page4826.html
Problem 94. df = pd.read_csv(filePath, header=None)
File "C:\..\lib\site-packages\pandas\io\parsers\readers.py", line 912, in read_csv
return _read(filepath_or_buffer, kwds)
File "C: \..\lib\site-packages\pandas\io\parsers\readers.py", line 583, in _read
return parser.read(nrows)
File "C: \..\lib\site-packages\pandas\io\parsers\readers.py", line 1704, in read
) = self._engine.read( # type: ignore[attr-defined]
File "C:\ \..\\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 234, in read
chunks = self._reader.read_low_memory(nrows)
File "pandas\_libs\parsers.pyx", line 812, in pandas._libs.parsers.TextReader.read_low_memory
File "pandas\_libs\parsers.pyx", line 873, in pandas._libs.parsers.TextReader._read_rows
File "pandas\_libs\parsers.pyx", line 848, in pandas._libs.parsers.TextReader._tokenize_rows
File "pandas\_libs\parsers.pyx", line 859, in pandas._libs.parsers.TextReader._check_tokenize_status
File "pandas\_libs\parsers.pyx", line 2025, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 10, saw 14
skiprows: some lines below can output error messages in some enviroments: code:
![Skip n rows from the start while reading a csv file](images3/4846b.png)
Input:
![Skip n rows from the start while reading a csv file](images3/4846a.png)
Output:
![Skip n rows from the start while reading a csv file](images3/4846c.png)
Problem 93. Error when .bat (batch) files for Command Prompt Windows:
xxx.bat is not recognized as an internal or external command,
operable program or batch file.
Origin: The .bat file is stored in a network folder instead of a folder in C: drive.
Note: some people mentioned that batch file only runs properly from C: drive.
Problem 92. Traceback (most recent call last):
dmFile = r"C:\GlobalSino20230219\EM\DM3_4 Matlab\EELS map\EELS test spectrum image.dm3"
img = hs.load(dmFile)
File "C:\0Python\Test.py", line 44, in <module>
img_crop = img.isig[90.0:100.0, 20:60]
return self.obj._slicer(slices, self.isNavigation, out=out)
array_slices = self._get_array_slices(slices, isNavigation)
raise IndexError("too many indices")
IndexError: too many indices
Origin: This only calls "img = hs.load('STEM.dm3') " instead of a EELS map.
Problem 91. AttributeError: 'NoneType' object has no attribute 'append'
myList = myList.append('Good')
Solution: remove "myList = ", namely, leave "myList.append('Good')" only.
Problem 90. Traceback (most recent call last):
File "C:\GlobalSino20230219\ICs\MostSimilar2410.py", line 5, in <module>
from embedding_encoder import EmbeddingEncoder
ModuleNotFoundError: No module named 'embedding_encoder'
Origin: missing the code line of "embedder = SentenceTransformer('all-MiniLM-L6-v2')".
Problem 89. Traceback (most recent call last):
File "C:\GlobalSino20230219\ICs\MostSimilar2410.py", line 4, in <module>
from sentence_transformers import SentenceTransformer, util
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python310\lib\site-packages\sentence_transformers\__init__.py", line 3, in <module>
from .datasets import SentencesDataset, ParallelSentencesDataset
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python310\lib\site-packages\sentence_transformers\datasets\__init__.py", line 1, in <module>
from .DenoisingAutoEncoderDataset import DenoisingAutoEncoderDataset
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python310\lib\site-packages\sentence_transformers\datasets\DenoisingAutoEncoderDataset.py", line 1, in <module>
from torch.utils.data import Dataset
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\__init__.py", line 119, in <module>
dlls = glob.glob(os.path.join(th_dll_path, '*.dll'))
AttributeError: module 'glob' has no attribute 'glob'
Origin of the problem: the parent folder has a file glob.py.
![glob.py](images2/4806n.png)
Problem 88. Pyautogui click won't register click on window of application on my desktop.
Answer: Some applications, like certain video games, have protection against this kind of stuff.
Problem 87. Reason of the problem: Zero free harddrive.
Traceback (most recent call last):
File "C:\....py", line 57, in <module>
driver = webdriver.Chrome(service = ser, options=chr_options)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "C:\Users\xx\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__
RemoteWebDriver.__init__(
File "C:\Users\xx\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__
self.start_session(capabilities, browser_profile)
File "C:\xx\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: failed to write prefs file
Stacktrace:
Backtrace:
(No symbol) [0x005DDCE3]
Problem 86. import email_pre as ep
ModuleNotFoundError: No module named 'email_pre'.
Solution: pip install email
Problem 85. UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte.
Solution: import pandas as pd
data = pd.read_csv(filename, encoding= 'unicode_escape')
Problem 85. Traceback (most recent call last): code:
File "C:/GlobalSino2/ICs/getCoorOnClick.py", line 14, in <module>
im.show()
AttributeError: 'NoneType' object has no attribute 'show'
Origin of the error: The order of "show" and "save" is not correct.
Wrong:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806l.png)
Correct:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806m.png)
Problem 84. Does not show image.
Fail code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806j.png)
Working code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806k.png)
Problem 83. apply_model(lr, x_train,x_val,y_train,y_val). (<code>).
File "C:/GlobalSino2/ICs/Word_Embeddings_SVM.py", line 219, in apply_model
img_pred_label.show()
AttributeError: 'ConfusionMatrixDisplay' object has no attribute 'show'
Fail code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806h.png)
Working code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806i.png)
Problem 82. fig_ax1_c = fig_ax1_c.figure. (<code>).
AttributeError: 'list' object has no attribute 'figure'
Fail code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806f.png)
Working code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806g.png)
Problem 81. AttributeError: 'AxesSubplot' object has no attribute 'savefig'. (<code>)
Fail code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806d.png)
Working code:
![AttributeError: 'AxesSubplot' object has no attribute 'savefig'](images2/4806e.png)
Problem 80. selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element.
Origin: It takes time to load the webpage; and thus the detection of webelement wasn't happening.
Solution A: below the code driver = webdriver....(), add two code lines:
driver.maximize_window() # maximizes the web window.
driver.implicitly_wait(20) # Gives an implicit wait for 20 seconds.
Solution B: The element is inside an iframe.
Solution C:
import time
time.sleep(30)
Solution D: (Not proved):
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "xyz"))
)
finally:
driver.quit()
Problem 79. x_data = tf.placeholder(tf.float32, shape=[100])
AttributeError: module 'tensorflow' has no attribute 'placeholder'.
Root cause: In TensorFlow 2.0, tf.placeholder is no longer in use. A placeholder is a variable that we will assign data to at a later point. It allows us to create operations and build the computation graph without the data. In TensorFlow 2.0, we can use tf.function to execute graph operations.
Problem 78. selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable.
Root cause: find_element(By.XPATH, "") is used to fill in a box by send_key("xyz"). E.g.:
element = driver.find_element(By.XPATH, "abc"). Here, abc is obtained by right click mouse, with "Copy full XPath", to get full path.
element.send_key("xyz"). Here, xyz is the content to be filled into the box.
![element.send_key("xyz")](images2/4806c.png)
Solution: find_element(CSS_SELECTOR, "abc") is used to fill in a box by send_key("xyz"). E.g.:
element = driver.find_element(CSS_SELECTOR, "abc"). Here, abc is obtained by "SelectorsHub > Copy Relative cssSelector".
element.send_key("xyz"). Here, xyz is the content to be filled into the box.
Problem 77. [[2 4 5 9 0 4 0]
[4 0 4 1 7 0 0]
[1 4 8 4 9 4 0]
[6 0 3 0 3 2 0]
[7 7 6 6 2 6 0]
[3 2 0 4 0 2 5]
[1 2 0 4 0 9 6]]
Traceback (most recent call last):
File "C:/GlobalSino2/ICs/HeatmapThreshold.py", line 24, in <module>
Farms[Farms < 5] = np.nan
ValueError: cannot convert float NaN to integer.
Solution:
First, onvert the integers to float. code:
![Replace a letter by seek](images2/4806b.png)
Problem 76.
Problem 76.A.
Traceback (most recent call last):
File "C:/GlobalSino2/ICs/pywinauto.py", line 4, in <module>
from pywinauto.application import Application
File "C:\GlobalSino2/ICs\pywinauto.py", line 4, in <module>
from pywinauto.application import Application
ModuleNotFoundError: No module named 'pywinauto.application'; 'pywinauto' is not a package
Solution: pywinauto is not applicable in Python 3.10, but it works in Python 3.8.
Problem 76.B.
Traceback (most recent call last):
File "C:/0Python/Codes/Code2.py", line 3, in <module>
from pywinauto.application import Application
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python38\lib\site-packages\pywinauto\__init__.py", line 59, in <module>
import win32api # noqa: E402
ImportError: DLL load failed while importing win32api: The specified module could not be found.
Solution: pip install pywin32==300 --upgrade
Problem 75. Traceback (most recent call last):
myText = textFile.read()
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 9336: character maps to <undefined>
Best solution:
textFile = open(r"C:\GlobalSino2\ICs\4304ForWordCloud.txt", encoding="utf8")
Other solutions:
If such characters are unneeded, they can be replaced by question marks, with:
file = open(filename, errors='replace')
file = open(filename, errors='ignore')
Specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):
file = open(filename, encoding='cp437')
(code)
Problem 74. print(classification_report(y0_test_decode, y0_pred_decode, target_names=faulty_case)) (code)
ValueError: Number of classes, 7, does not match size of target_names, 8. Try specifying the labels parameter.
Origin: target_names > classes.
Explaination:
labels should correspond to the values actually found in y_true and y_pred.
target_names should map `labels` to names for display.
"Solution 1 ": The code line can be removed if it is not "needed".
Solution 2: Give more documents for each class existing in my dataset
Solution 3: Pass in target_names and labels with the unseen label and target name, with the code below:
y0_pred_decode = np.array([0, 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 2, 1, 0])
y0_test_decode = np.array([0, 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 2, 1, 0])
labels = np.array([0, 1, 2, 3, 4, 5, 6])
target_names = [f"class{i}" for i in range(7)]
print(classification_report(y_true, y_pred, labels=labels,
target_names=target_names, zero_division=0))
Problem 73:
In general, one cannot safely write to a file while reading, it is better to read the file into memory, update it, and rewrite it to file.
Problem 72:
"ValueError: could not convert string to float:" in "float(row[22])" for csv files. code.
Solution: Set the empty cells in the csv file to 0.0 since the empty cells cause the problem.
Problem 71: Something does not work:
3.a: Does not work without "r": MyPresentation.save('C:\GlobalSino\images\TestImages\20211101_Local\My_presentation.pptx')
Works with "r": MyPresentation.save(r'C:\GlobalSino\images\TestImages\20211101_Local\My_presentation.pptx')
3.b: locateCenterOnScreen does not work:
"region=()" is defined by a too small area
3.c. No error messages show up, but some function does not work:
i) Solution A: Probably needs to give some time to let the execution to complete, otherwise this process is just
skipped directly.
ii) Solution B: Do not use function.
iii) Other common issues and troubleshooting steps are:
-
Syntax Errors: Ensure that there are no syntax errors in your function definition. Check for correct indentation, colons, and proper use of parentheses. Python is sensitive to indentation, and incorrect indentation can lead to syntax errors.
-
Incorrect Indentation: Python relies on indentation to define blocks of code. Make sure that the statements inside your function are indented correctly. Consistent and proper indentation is crucial for Python code to work.
-
Invalid Function Name: Check if the function name follows the rules for naming identifiers in Python. Function names should start with a letter or underscore, followed by letters, numbers, or underscores.
-
Variable Scope: Ensure that all the variables used in the function are properly defined within the function or passed as arguments. Variables defined outside the function may not be accessible inside the function unless explicitly declared as global.
-
Missing return Statement: If your function is supposed to return a value, make sure you have a return statement with the appropriate value. Functions without a return statement implicitly return None.
-
Function Call: Make sure you are calling the function correctly. Use the correct function name and pass the required arguments, if any.
-
Importing Modules: If your function relies on modules or libraries, ensure that you have imported them correctly at the beginning of your script.
-
Exception Handling: Check if there are any exceptions or errors being raised during the execution of your function. Adding try and except blocks can help you identify and handle exceptions.
-
Print Statements: Insert print statements within your function to trace the flow of execution. This can help you identify where the function is failing or producing unexpected results.
-
Check for Typos: Carefully review your code for typos in variable names, function names, and keywords. Even a small typo can lead to errors.
|
3.d. This does not work since a space after "SIVB" is needed.
![This does not work since a space after "SIVB" is needed](images/4806ao.png)
Problem 70:
Wrong indication of an error:
Input CSV file:
![csv.reader](images/4806c.PNG)
File "C:/GlobalSino/ICs/page4853dataset_2.py", line 18, in LoadDataset
dataset[x][y] = int(dataset[x][y])
ValueError: invalid literal for int() with base 10: '148,55,168,75,S'. The problem is at code:
![csv.reader](images/4806b.PNG)
Working code is code:
![csv.reader](images/4806.PNG)
Problem 69: code:
Traceback (most recent call last):
File "C:/GlobalSino/ICs/page4853histogram.py", line 19, in <module>
sns.displot(dataset, X="Protein", hue='Sale')
ValueError: The following variable cannot be assigned with wide-form data: `hue`
![Plot histogram in numpy](images/4806d.PNG)
Solution: changed capital "X" to low case "x".
sns.displot(dataset, x="Protein", hue='Sale')
Problem 68: code:
![](images/4806e.PNG)
Traceback (most recent call last):
File "C:\GlobalSino\ICs\page4853KNN6.py", line 68, in <module>
y_hat_test = KNN(X_train, X_test, Y_train, Y_test, k_val=5)
NameError: name 'iloc' is not defined
Reason: this was "," instead of ".". Correct one is:
![](images/4806f.PNG)
Problem 67: To check if a variable is already defined in python:
# for local
if 'x' in locals():
print("x exists.")
# for globals
if 'x' in globals():
print("x exists.)
Problem 66: Traceback (most recent call last):
File "C:\GlobalSino\images\04-2.py", line 58, in <module>
Diode_circuit(Input_Voltage)
File "C:\GlobalSino\images\04-2.py", line 50, in Diode_circuit
thewriter.writerow ({'Input_V': float(analysis.nodes[1]),'Output_V': float(analysis.nodes[2])})
Correct one is (namely, it cannot be a number of the node in "nodes[]"):
, e.g. code.
Problem 65: PermissionError because the csv file has been opened:
Traceback (most recent call last):
File "C:/GlobalSino/ICs/page4853Diode_circuit.py", line 50, in <module>
Diode_circuit(Input_Voltage)
File "C:/GlobalSino/ICs/page4853Diode_circuit.py", line 38, in Diode_circuit
with open (r'C:\GlobalSino\images\Electrical_Simulation.csv', 'a', newline ='') as my_csv_file:
PermissionError: [Errno 13] Permission denied: 'C:\\GlobalSino\\images\\Electrical_Simulation.csv'
Problem 64: Dictionary error:
Traceback (most recent call last):
File "C:/GlobalSino/ICs/page4853Switch_circuit.py", line 84, in <module>
Switch_circuit(Input_Voltage)
File "C:/GlobalSino/ICs/page4853Switch_circuit.py", line 73, in Switch_circuit
thewriter.writerow ({'Middle': float(analysis.nodes['middle']),'Output_V': float(analysis.nodes['out_put'])})
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python39\lib\csv.py", line 154, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python39\lib\csv.py", line 149, in _dict_to_list
raise ValueError("dict contains fields not in fieldnames: "
ValueError: dict contains fields not in fieldnames: 'Middle'
![Dictionary error](images/4806h.PNG)
Problem 63:
TypeError: Need to pass the same number of values.
Wrong code:
![missing 1 required positional argument](images/4806i.PNG)
Correct code:
![missing 1 required positional argument](images/4806j.PNG)
Problem 62: Need to pass the same number of values.
add() takes 2 positional arguments but 3 were given.
Wrong code:
![missing 1 required positional argument](images/4806K.PNG)
Problem 61: Replacement code if there is an error message below:
'''
When there is a error message (see below) with the script at:
https://www.globalsino.com/ICs/page4853Web_Automation2.py
Error message:
MyWebDriver = webdriver.Chrome(r'C:\mu\bin\chromedriver')
DeprecationWarning: executable_path has been deprecated, please pass in a Service object
However, in "normal" condition, the script gives an error message:
driver = webdriver.Chrome(service=Service())
TypeError: __init__() missing 1 required positional argument: 'executable_path'
'''
code:
![Replacement code if there is an error message below](images/4806l.PNG)
Problem 60: TypeError: object of type 'numpy.int64' has no len()
Traceback (most recent call last):
File "C:/GlobalSino/ICs/page4853Selenium_Auto.py", line 20, in <module>
VIN_number_input.send_keys(entry['Last5ofVIN'])
...
File "C:\Users\yougui\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\common\utils.py", line 150, in keys_to_typing
for i in range(len(val)):
TypeError: object of type 'numpy.int64' has no len()
Reason to the problem:
The csv sheet has numbers and pd is reading it as int64 instead of string that you want. The only thing that you may need is to classify it as a string (e.g. code):
.send_keys(str(i))
Problem 59: No correct values have been necessarily provided to the script:
Traceback (most recent call last):
File "C:/GlobalSino/ICs/page4853positions.py", line 12, in <module>
print(Search_img[0])
TypeError: 'NoneType' object is not subscriptable
Problem 58: If there is no such feature on the main screen, then a problem occurs (code:):
Traceback (most recent call last):
File "C:\GlobalSino\images\Testing.py", line 6, in <module>
x, y, h, w = Search_img
TypeError: cannot unpack non-iterable NoneType object
The feature which was looked for was:
![Ok](images/4732g.PNG)
But the feature on the screen was:
![Ok](images/4806m.PNG)
Problem 57: cannot import name '_registerMatType' from 'cv2.cv2'
Traceback (most recent call last):
File "C:\GlobalSino\images\Testing.py", line 1, in <module>
import cv2
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python39\lib\site-packages\cv2\__init__.py", line 9, in <module>
from .cv2 import _registerMatType
ImportError: cannot import name '_registerMatType' from 'cv2.cv2'
To fix this issue, you need to uninstall opencv-python and then reinstalling it with pip:
pip uninstall opencv-python
pip install opencv-python
Problem 56: No module named 'mediapipe'
File "C:\GlobalSino\images\Testing.py", line 2, in <module>
import mediapipe as mp
ModuleNotFoundError: No module named 'mediapipe'
Origin: MediaPipe supports Python 3.6 to 3.8, but it does not support have Python 3.9.
Problem 55: Can I loop PyAutoGUI's locateCenterOnScreen until the image is found?
Based on PyAutoGUI's source code the function locateCenterOnScreen uses pyscreeze:
https://github.com/asweigart/pyautogui/blob/master/pyautogui/__init__.py#L205
@raisePyAutoGUIImageNotFoundException
def locateCenterOnScreen(*args, **kwargs):
return pyscreeze.locateCenterOnScreen(*args, **kwargs)
locateCenterOnScreen.__doc__ = pyscreeze.locateCenterOnScreen.__doc__
Based on pyscreeze's source code the function locateCenterOnScreen has a parameter minSearchTime:
https://github.com/asweigart/pyscreeze/blob/master/pyscreeze/__init__.py#L409
Therefore, it already has a looping mechanism built in, try giving a minSearchTime
Problem 54: Python testing data on GlobalSino:
Group 1: locateCenterOnScreen and locateOnScreen testing:
https://www.globalsino.com/ICs/page4653.html
C:\GlobalSino\ICs\images\4732g.PNG
Group 2: https://www.globalsino.com/ICs/ExampleFiledUsedINtestingPython
Problem 53: When run "locateCenterOnScreen" from "pyautogui" with part of the script (see below), got OSError: Failed to read *\*.png because file is missing, has improper permissions, or is an unsupported or invalid format.
Part of the script:
However, it works if the code is below:
Problem 52: coordinate = pg.locateCenterOnScreen(os.path.join(root, name)). OSError: Failed to read C:\0Python\images\screenshots\foundFileList.txt because file is missing, has improper permissions, or is an unsupported or invalid format
Original of the problem: The target folder contains non-image file(s), e.g. the ".txt" file here.
Problem 51: This script is created for "launch the existing opened application if there is or start a new one if there is not"; however, the steps after the red line do not go through with the existing of circled codes: The reason of the error is that "def " function is a local function, so that the code below does not work: code:
However, the one below works: code:
![Launch the existing opened application if there is or start a new one if there is not](images/4806p.PNG)
Problem 50: No module named 'termios':
termios requires the termios module, it will work only on Unix, i.e. there is no termios for Windows.
Problem 49: No such file or directory: 'C:\x8211101_
wb = load_workbook('C...)
No such file or directory: 'C:\x8211101_
Error cause:
The "r" in the code was missing.
![Launch the existing opened application if there is or start a new one if there is not](images/4806q.png)
Problem 48: Error in " insert_columns":
File "C:/GlobalSino2/ICs/page4853insert_columns.py", line 14, in <module>
ws.insert_cols("C")
TypeError: 'str' object cannot be interpreted as an integer:
ws.insert_cols("C") # insert_columns
Then, the code needs to be corrected to (code):
ws.insert_cols(3) # insert_columns
Problem 47: ModuleNotFoundError: No module named 'clipboard':
Solution: Use F5 to run the program instead of running it on cmd (Command Prompt).
Problem 46a: Does not have response (nothing happens) when running a script.
Origin: Probably there is a code line, which limits the function or file (e.g. preventing to call the older image, pptx files with time functions ).
Problem 46b. Does not have response (nothing happens) when run def xyz() function, with the code below:
![function](images/4806za.png)
Solution with "()":
![function](images/4806zb.png)
Problem 45. ctypes.ArgumentError: argument 1: <class 'ValueError'>: embedded null character when C:\0xyz, or C:\xyz\0\ (here "0" can be any number).
Origin of the error message: In Python, '\0' means NULL, \1 is equivalent to re.search(...).group(1), \2 is handled as a special character ...
Problem 44: 'Word2Vec' object is not subscriptable
Origin: This error message appears when gensim 4 is used incorrectly. The operation between gensim 4 and gensim 3 are different.
An alternative solution: pip install gensim==3.2 (This will uninstall gensim 4 and then install gensim 3.2). However, this metnod is not
recommended, one reason is that This is a slow version of gensim.models.word2vec. However, if this is used, then the code needs to be changed to:"model = Word2Vec(sent, min_count=1, size= 50,workers=3, window =3, sg = 1)" from " model = Word2Vec(sent, min_count=1, vector_size= 50,workers=3, window =3, sg = 1)"
Best solution: Stay with gensim 4, but use "print(model.wv['Toyota Camry'])" instead of "print(model['Toyota Camry'])".
However, in a defined fucntion "def ...", no ".wv" is needed to add.
Problem 43: IndexError: list index out of range when "command = sys.argv[1]" is used.
Origin: sys.argv is the list of command line arguments passed to a script, where sys.argv[0] is the script name itself.
Solution: use ''command = sys.argv[1] if len(sys.argv) > 1 else '.' " to replace "command = sys.argv[1]".
Problem 42: 'utf-8' codec can't decode byte 0x92 in position 18: invalid start byte
use "df1 = pd.read_csv("https://...csv", sep=";", encoding='cp1252')" instead of "df1 = pd.read_csv("https://...csv", sep=";")"
Problem 41: OSError: [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a Python package or a valid path to a data directory.
A simple solution:
from spacy.lang.en import English
nlp=English()
Another solution:
pip3 install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz
Problem 40: RuntimeError: you must first build vocabulary before training the model
The csv file is not correct so that the training cannot be done.
Problem 39: newVed = [nltk.word_tokenize(Make) for Make in newsMake]
**********************************************************************
Resource [93mpunkt[0m not found.
Please use the NLTK Downloader to obtain the resource:
[31m>>> import nltk
>>> nltk.download('punkt')
[0m
For more information see: https://www.nltk.org/data.html
Attempted to load [93mtokenizers/punkt/english.pickle[0m
Searched in:
- 'C:\\Users\\ygliao/nltk_data'
- 'C:\\Users\\ygliao\\AppData\\Local\\Programs\\Python\\Python39\\nltk_data'
- 'C:\\Users\\ygliao\\AppData\\Local\\Programs\\Python\\Python39\\share\\nltk_data'
- 'C:\\Users\\ygliao\\AppData\\Local\\Programs\\Python\\Python39\\lib\\nltk_data'
- 'C:\\Users\\ygliao\\AppData\\Roaming\\nltk_data'
- 'C:\\nltk_data'
- 'D:\\nltk_data'
- 'E:\\nltk_data'
- ''
**********************************************************************
Solution:
Add a code line "nltk.download('punkt')" before the line of "newVed = [nltk.word_tokenize(Make) for Make in newsMake]"
Problem 38: AttributeError: 'Word2Vec' object has no attribute 'most_similar', when "print(model.most_similar("Mitsubishi"))" is used.
Solution: use the code line below:
print(model.wv.most_similar("Mitsubishi"))
Problem 37: pip install google.colab (has errors)
pip install google-colab (has errors)
Problem 36: model = KeyedVectors.load_word2vec_format('C:\0Python\AchiveFiles\GoogleNews-vectors-negative300.bin', binary = True, limit=10000)
ValueError: embedded null character
Solution: (add a "r" in front of the file path):
model = KeyedVectors.load_word2vec_format(r'C:\0Python\AchiveFiles\GoogleNews-vectors-negative300.bin', binary = True, limit=10000)
Problem 35: AttributeError: The vocab attribute was removed from KeyedVector in Gensim 4.0.0. When the code lines below are used:
X = model[model.wv.vocab]
words = list(model.wv.vocab)
Solution:
vocab = list(model.wv.key_to_index)
X = model.wv[vocab]
words = list(model.wv.index_to_key)
Problem 34: Error message when install seleniumbase:
Consider using the `--user` option or check the permissions. seleniumbase
Solution:
First step: The path was not correct. Update with the box in red below checked (it probably was not checked at the initial installation).
![Error message when install seleniumbase](images/4806zc.png)
Second step:
Option 1: Using pip3 install instead of pip install to install seleniumbase
Option 2: Upgrade pip first before installing seleniumbase (sometimes)
Problem 33: pyautogui.locateCenterOnScreen() returns None instead of coordinates when taking a screenshot by other ways rather than taking by pyautogui inbuilt function.
Solution: Take screenshots by pyautogui inbuilt function rather than taking a screenshot by WIN+Printscr or other tools since their pixel densities may be different in comparison to the ones used by pyautogui inbuilt function.
Problem 32: Possible error message when running the chromedriver.exe >> DeprecationWarning: executable_path has been deprecated, please pass in a Service object
i) To Solve DeprecationWarning: executable_path has been deprecated, please pass in a Service object Error Here executable_path is deprecated you have to use an instance of the Service() class as follows. s = Service('C:/Users/…/chromedriver.exe') and then driver = webdriver.Chrome(service=s) Now, Your error must be solved.
ii) To Solve DeprecationWarning: executable_path has been deprecated, please pass in a Service object Error Here executable_path is deprecated you have to use an instance of the Service() class as follows. s = Service('C:/Users/…/chromedriver.exe') and then driver = webdriver.Chrome(service=s) Now, Your error must be solved.
The code will also be changed to:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service # Adding
ser = Service(r"C:\...\chromedriver.exe") # Adding
op = webdriver.ChromeOptions() # Adding, but it can be removed
s = webdriver.Chrome(service=ser, options=op) # Adding
s = webdriver.Chrome(service=ser) # Adding, but removed "options=op"
Problem 31: Problem when "from pptx import Presentation":
cannot import name 'Presentation' from partially initialized module 'pptx' (most likely due to a circular import)
Origin of the problem: there is a file in the same folder called pptx.py. In this case, Python doesn't know whether to import your pptx module or the library.
Problem 30: AttributeError: type object 'By' has no attribute 'Tag_Name'
AttributeError: 'WebElement' object has no attribute 'sendKeys'
driver = webdriver.Chrome(r'C:\usr\local\bin\chromedriver')
DeprecationWarning: executable_path has been deprecated, please pass in a Service object (Code)
Original code:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
...
Correct code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
ser = Service(r"C:\usr\local\bin\chromedriver.exe")
driver = webdriver.Chrome(service=ser)
time.sleep(2)
driver.implicitly_wait(3)
driver.maximize_window()
time.sleep(2)
driver.get("https://secure.yatra.com/social/common/yatra/signin.htm")
time.sleep(3)
driver.find_element(By.TAG_NAME, "input").send_keys("yougui.liao@gmail.com")
Problem 29: Problem using win32com.client.Dispatch on Windows 64bit. IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch).
Origin of the problem: 64bit processes can't use 32bit COM objects
Solution: The easiest answer is to install the 32bit Python and 32bit pywin32 extensions.
Problem 28b: Another weird, strange, unknown problem is related to locateCenterOnScreen() function. Please refer to "Locate center on screen by locateCenterOnScreen() with reference options" at page4651.
Problem 28a: One weird, strange, unknown problem is that the output (e.g. csv) file cannot be saved through unix/Linux in case the file is opened, which does not give permission to overwrite the existing file. Plus, the very bad thing is that the Python execution does not produce any error messages on unix.
Problem 27: Google chrome closes immediately after being launched with selenium. See page4437.
Problem 26: "Unicode Error: unicodeescape codec can't decode bytes in position
from "source = "C:\Users\yyliao\Downloads""
from "source = r'C:\Users\yyliao\Downloads'"
Origin of problem :
\U in "C:\Users... starts an eight-character Unicode escape, such as \U00014321. The escape is followed by the character 's', which is invalid.
Solution 1: duplicate all backslashes: "source = "C:\\Users\\yyliao\\Downloads""
Solution 2: prefix the string with r (to produce a raw string): "source = r"C:\Users\yyliao\Downloads""
Problem 25: Troubleshooting: Error occurs when running the script below (code):
![Move files from one directory to another (the file must already exist)](images/4435h.png)
Error is:
File "C:/GlobalSino2/ICs/page4853movFiles5.py", line 16, in <module>
os.rename(source, destination)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\yyliao\\Downloads\\AAPL.csv' -> 'C:\\0Python\\Stocks\\IndividualStocks\\AAPL.csv'
Correct script (code):
![Move files from one directory to another (the file must already exist)](images/4435i.png)
Problem 24:
Traceback (most recent call last):
File "C:\GlobalSino2\images\04-2.py", line 11, in <module>
print(row["Volume"])
TypeError: list indices must be integers or slices, not str
Code:
![Move files from one directory to another (the file must already exist)](images/4806ab.png)
Input:
![Move files from one directory to another (the file must already exist)](images/4806aa.png)
Correct code:
![Move files from one directory to another (the file must already exist)](images/4806ac.png)
Problem 23: IndentationError: unexpected indent error
Origin: The empty line below causes the error.
![The empty line below causes the error](images/4806ad.png)
Solution:
![The empty line below causes the error](images/4806ae.png)
Problem 22. TypeError: unsupported operand type(s) for -: 'str' and 'str'.
Origin: the csv cell are string.
![The empty line below causes the error](images/4806af.png)
Solution:
![The empty line below causes the error](images/4806ag.png)
Problem 21. Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details.
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806ah.png)
There are multiple things that can cause the problem, but fortunately Google gives us a way to learn the specific reason. This helps us know what to do to fix it. Notice the last part of the error says to open the JavaScript console for “technical details”.
Step 1: Open the JavaScript console in different browsers, e.g. opening the "Console" panel of Chrome’s DevTools with Ctrl + Shift + J.
Step 2: The most common errors are:
ApiNotActivatedMapError – API is not enabled
MissingKeyMapError – An API key is not being used
RefererNotAllowedMapError – Key doesn’t allow your URL
InvalidKeyMapError – The API key used is incorrect
How to Fix Other Errors – More errors are possible
For instance, the one blow is "ApiNotActivatedMapError – API is not enabled":
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806ai.png)
Step 3: Fix the error above:
Go to https://console.developers.google.com/apis/library
Under “Maps”, click “View All” to see all API’s.
Click the API you’re using. Our themes and plugins use the Maps JavaScript API, Maps Static API and Geocoding API. Your product may use something different but the JavaScript API is most common for a website.
Click the Enable button at the top and wait a few minutes for the changes to take effect (Google says changes can take up to 5 minutes).
Repeat for other API’s you’re using (remember, the themes and plugins here use the Maps JavaScript, Maps Static and Geocoding API’s).
Step 4: The same error message shows up and an new error appears:
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806ah.png)
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806aj.png)
Step 5: Address this problem above:
RefererNotAllowedMapError is the most common error we’ve seen apart from not using a key.
Go to https://console.developers.google.com/apis/credentials
Click your API key’s name to edit its settings.
Under Application restrictions, make sure “HTTP referrers (web sites)” is selected and that you have added the two entries below (replacing yourname.com with your own domain). Both are necessary and be sure that have you appended /* to the end.
yourname.com/*
*.yourname.com/*
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806ak.png)
Click the Save button then wait a few minutes for the change to take effect (Google says it can take up to 5 minutes).
Step 6: An unsafe method to address the problem above is that you do not restrict the key.
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806al.png)
Problem 20. Google Maps shows "For development purposes only" when calling Google Map:
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806am.png)
Answer: Google Maps is no longer free. You have to associate a credit card so that you can get billed. Don’t worry as they won’t charge you for anything unless you have over 20,000 people viewing your map each month, they do this by providing users with a $200 credit each month.
Fix the problem: Create a Google Cloud Account by clickig "Get started" at the link.
![Oops! something went wrong this page didn't load google maps correctly see the javascript console for technical details](images/4806an.png)
Check your charges: https://console.cloud.google.com/billing/01F014-0A32DD-9893D9?project=studied-client-347407
Problem 19: TypeError: annotate() missing 1 required positional argument: 'text': Solution: "insted of s = xxx use text = xxx":
# idaho.apply(lambda x: ax.annotate(s=x.NAME, xy=x.geometry.centroid.coords[0], ha='center', fontsize=7),axis=1)
idaho.apply(lambda x: ax.annotate(text=x.NAME, xy=x.geometry.centroid.coords[0], ha='center', fontsize=7),axis=1)
Problem 18: df.loc[i, 2] = location.latitude
AttributeError: 'NoneType' object has no attribute 'latitude'
AttributeError: 'NoneType' object has no attribute 'longitude'
Solution: remove the row from the csv file.
Problem 17: OSError: [WinError 1314] A required privilege is not held by the client (for symlink), when running "os.symlink(path1, sym_link)":
Solution: Run the Program as Administrator:
![Run the Program as Administrator](images/4806zd.png)
Problem 16: FileExistsError: [WinError 183] Cannot create a file when that file already exists:
Origin: The existing file is below (see details at page4399):
![Check if file exists or not, and then open it if there is](images/4399d.png)
Problem 15: FileExistsError: [WinError 183] Cannot create a file when that file already exists:
Case:
import shutil
src=r"C:\xyz"
dst=r"C:\ZZZ"
shutil.copytree(src,dst, symlinks=False, ignore=None)
FileExistsError: [WinError 183] Cannot create a file when that file already exists:
However, the the folder of C:\ZZZ is actually empty.
Explaination:
Python 3.8 now have support of dirs_exist_ok parameter. This won't give that error anymore and overwrite the destination folder in case it already exists.
Solution:
Use code with Python 3.8 or higher: shutil.copytree(src, dst, dirs_exist_ok=True)
Problem 14. Plot images from data, with names, in a csv files (see details at page4806): code:
![Find the best similarity with Word2Vec Models/word embeddings](images/4500d.png)
With the same code above, but there is an error showing if the csv file has only two columns as shown below:
<_csv.reader object at 0x000001A5BCA70640>
['Mike', '41']
Traceback (most recent call last):
File "C:\GlobalSino2\ICs\page4853WithoutAxis.py", line 21, in <module>
y.append(int(float(row[2])))
IndexError: list index out of range
Input:
Problem 13: NamEerror: name 'shutil' is not defined.
NameError: name 'glob' is not defined
Solution: they need to be imported by "import ...".
Problem 12: Traceback (most recent call last):
File "C:/GlobalSino2/ICs/page4853Schedule3.py", line 15, in <module>
os.makedirs(new_path)
mkdir(name, mode)
ValueError: mkdir: embedded null character in path
Origin: missing a "r" in front:
![Find the best similarity with Word2Vec Models/word embeddings](images/4806ap.png)
Solution:
![Find the best similarity with Word2Vec Models/word embeddings](images/4806aq.png)
Problem 11: OpenCV or cv2 >>
AttributeError: 'NoneType' object has no attribute 'shape'
Origin: Somewhere a function which should return a image just returned None and therefore has no shape attribute. Use print(theImage) to check if it is true.
Problem 10: SyntaxError: ‘break’ outside loop:
A break statement instructs Python to exit a loop. The purpose of a break statement is to terminate a loop abruptly by triggering a condition. So, the break statement can only be used inside a loop (e.g. if loop). If a break statement is used outside of a loop, for example, in an if statement without a parent loop, then the error message shows up.
There are many alternative ways to fix the problem. See break functions.
Problem 9: Traceback (most recent call last):
File "C:/GlobalSino2/ICs/page4354attribute2.py", line 13, in <module>
print(XYZ())
File "C:/GlobalSino2/ICs/page4354attribute2.py", line 9, in XYZ
XYZ.ThisIsTheAttribute += 1
AttributeError: 'function' object has no attribute 'ThisIsTheAttribute'
Error: Code:
![Automatically Review, Scroll, Click Webpage and Its Link](images/page4354c.png)
Output:
![Automatically Review, Scroll, Click Webpage and Its Link](images/page4354d.png)
Problem 8: UnboundLocalError: local variable 'number' referenced before assignment. Code.
![Automatically Review, Scroll, Click Webpage and Its Link](images/page4806a.png)
Solution: we either can use 'global' keyword or global() function: Code.
![Automatically Review, Scroll, Click Webpage and Its Link](images/page4806b.png)
Output:
![Automatically Review, Scroll, Click Webpage and Its Link](images/page4806c.png)
Problem 7: Traceback (most recent call last):
File "C:/GlobalSino2/ICs/SimpleResize.py", line 18, in <module>
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
cv2.error: OpenCV(4.5.4) :-1: error: (-5:Bad argument) in function 'resize'
> Overload resolution failed:
> - Can't parse 'dsize'. Sequence item with index 0 has a wrong type
> - Can't parse 'dsize'. Sequence item with index 0 has a wrong type
Solution: add "round" or "int" (since pixel cannot be a float number):
![Automatically Review, Scroll, Click Webpage and Its Link](images/4806ba.png)
Problem 6. ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.
Solution: E.g. change to "max_iter=10000" from "max_iter=1000"
![Automatically Review, Scroll, Click Webpage and Its Link](images/4806abc.png)
Problem 5. UnicodeEncodeError: 'charmap' codec can't encode character '\ufb01' in position 0: character maps to <undefined>
Solution: Replace "(with open(fname, "w") as f:)"
with "(with open(fname, "w", encoding="utf-8") as f:)".
Problem 4. PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736].
Solution: Replace "(pdf = PdfFileReader(pdf_file_path,))" with "(pdf = PdfFileReader(pdf_file_path, strict=False))" (see example)
Problem 3. for line in f:
File "C:\Users\yyliao\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1684: character maps to <undefined>
Solution: Replace "(with open(theBankB) as f)" with "(with open(theBankB, encoding = 'utf-8') as f)".
Problem 2. cv2.imread ... rgb2gray
if rgb.ndim == 2:
AttributeError: 'NoneType' object has no attribute 'ndim'
Origin of the error: the imread call fails is usually that the path to the file is wrong.
Problem 1. "ValueError: Shapes (None, 8) and (None, 9) are incompatible" when using tensorflow and keras. (code)
![Automatically Review, Scroll, Click Webpage and Its Link](images/4806ar.png)
Origin: problem is at "output_tensor = layers.Dense(9, activation='softmax')(dense_2)"
(see the output below with this code line above)
![Automatically Review, Scroll, Click Webpage and Its Link](images/4806at.png)
Solution: The nb_classes (which is "9" above) should be same as y_train.shape[1] (which is "8" in a code line output).
>> # E.g. model.add(tf.keras.layers.Dense(nb_classes, activation='softmax'))
The code works after changed to " output_tensor = layers.Dense(8, activation='softmax')(dense_2)"
(see the output below with this code line above)
![Automatically Review, Scroll, Click Webpage and Its Link](images/4806as.png)
|